Skip to main content

vouch_core/
did_webvh.rs

1//! did:webvh v1.0 resolution, offline (DIF did:webvh v1.0,
2//! identity.foundation/didwebvh/v1.0).
3//!
4//! A did:webvh DID looks like a did:web DID with one extra part, the SCID:
5//!
6//! ```text
7//! did:webvh:QmXhVjFG6EBTosDastaaHMRypm2qSv4SMGctADsx878Yux:example.com
8//! ```
9//!
10//! Its DID document is not one file. It is a log (`did.jsonl`), one signed
11//! entry per version, each entry chained to the one before by a hash. The SCID
12//! is a hash of the first entry, so the DID itself commits to where its
13//! history starts. A resolver reads every entry, checks every hash and
14//! signature, and uses the last entry's `state` as the DID document.
15//!
16//! This is a port of the Python reference (`vouch/did_webvh.py`), and every
17//! rule, error code and fixed text is the same. The shared cases are in
18//! `test-vectors/did-webvh/vector.json`. The core never fetches: the caller
19//! fetches `did.jsonl` from [`log_url`] (https only, no redirects, a size cap,
20//! public addresses only) and hands the bytes to [`verify_log`].
21//!
22//! What is refused, explicitly: witnesses (`unsupported`), a DID that moves
23//! (`unsupported`), other method versions (`unsupported`), U-label domains
24//! (`unsupported`), DID URLs (`unsupported`), a deactivated DID
25//! (`deactivated`), and `null` parameters (`invalidDid`). Watchers are
26//! reported in the metadata and never contacted. A did:webvh DID is never
27//! treated as the did:web DID at the same location.
28//!
29//! The order of the checks decides which error a log with several problems
30//! reports, so it is the same in every language:
31//!
32//! 1. The bytes: the size limit, no byte order mark, UTF-8, then the lines
33//!    (split on `\n`; one final newline is allowed, no blank line, at most
34//!    `max_entries` lines, each at most `max_line_bytes`). Each line, in
35//!    order, must be one JSON object: no CRLF, nesting at most 64 levels, no
36//!    repeated member name, no number outside +/-(2^53 - 1), no lone
37//!    surrogate; exactly the members versionId, versionTime, parameters,
38//!    state and proof, of the right types; `proof` a non-empty list of at
39//!    most `max_proofs` objects. All lines are read before any entry is
40//!    verified.
41//! 2. Then each entry, in order: no entry after a deactivated one, or after
42//!    `updateKeys` was emptied when pre-rotation is off; the versionId; the
43//!    versionTime; the parameters; the pre-rotation commitment; the SCID; the
44//!    entry hash; every proof, in order; the state's id.
45//! 3. Then the log as a whole: some entry's `state.id` is the DID; the
46//!    version seen before is still in the log; the version query; and last,
47//!    that the selected version is not the deactivated one.
48//!
49//! Any failure refuses the whole log. Log proofs are checked with
50//! [`crate::data_integrity::hash_data`] and strict Ed25519, never with
51//! [`crate::data_integrity::verify_proof`], which also accepts an older
52//! signing input.
53//!
54//! Limits may be lowered, never raised past the reference's caps: 5 MiB, 1000
55//! entries, 4 proofs per entry, 32 update keys and 32 next-key hashes.
56//!
57//! For credential verification ([`crate::credentials::verify_with_did_webvh_log`],
58//! and grant issuers in a delegation chain through
59//! [`crate::delegation::ChainOptions::grant_logs`]), the caller hands the
60//! fetched logs over in a [`LogSet`]. Those logs are checked against the
61//! system clock ([`LogClock`]), as the reference resolves them, never against
62//! the time the credential is checked at; a fixed log clock is for tests and
63//! replays. The core keeps no record of the versions seen: the caller gives
64//! the version it saw before for each DID and keeps the latest one the set
65//! reports.
66//!
67//! serde_json keeps the last of two members with the same name, so the log
68//! lines are read here by a small reader of their own that refuses a repeated
69//! name, a number outside +/-(2^53 - 1) and a lone surrogate, in the same
70//! order as the reference's reader.
71
72use std::cell::RefCell;
73use std::collections::{BTreeMap, HashSet};
74use std::fmt;
75
76use serde_json::{json, Map, Number, Value};
77use sha2::{Digest, Sha256};
78
79use crate::error::{CoreError, Result};
80use crate::{jcs, keys, multikey, time};
81
82/// Every did:webvh DID starts with this (the trailing colon included, so a
83/// did:web DID never matches it, nor it a did:web prefix check).
84pub const PREFIX: &str = "did:webvh:";
85/// The one method version this resolver reads.
86pub const METHOD: &str = "did:webvh:1.0";
87const CRYPTOSUITE: &str = "eddsa-jcs-2022";
88const PROOF_TYPE: &str = "DataIntegrityProof";
89const PROOF_PURPOSE: &str = "assertionMethod";
90const SCID_PLACEHOLDER: &str = "{SCID}";
91/// How far ahead of the resolver's clock a versionTime may be, in seconds.
92pub const MAX_FUTURE_SECONDS: i64 = 300;
93/// The ttl when a log sets none, in seconds.
94pub const DEFAULT_TTL: i64 = 3600;
95/// The largest ttl, in seconds.
96pub const MAX_TTL: i64 = 1 << 31;
97/// The largest number every reader holds exactly (JavaScript and Go read JSON
98/// numbers as doubles), so a log hashes to the same bytes in every language.
99pub const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
100/// The largest log any caller may allow (5 MiB).
101pub const HARD_MAX_BYTES: usize = 5 * 1024 * 1024;
102/// The most entries any caller may allow. Every proof hashes its entry's
103/// proof options and every entry is hashed a few times, so this and the three
104/// counts below bound the work one log can ask for.
105pub const HARD_MAX_ENTRIES: usize = 1000;
106/// The most proofs on one entry any caller may allow.
107pub const HARD_MAX_PROOFS: usize = 4;
108/// The most keys in one `updateKeys` any caller may allow.
109pub const HARD_MAX_UPDATE_KEYS: usize = 32;
110/// The most hashes in one `nextKeyHashes` any caller may allow.
111pub const HARD_MAX_NEXT_KEY_HASHES: usize = 32;
112/// How deeply one log line may nest objects and lists.
113pub const MAX_LOG_DEPTH: usize = 64;
114
115/// The DID or its log is not valid.
116pub const INVALID_DID: &str = "invalidDid";
117/// No log, or no version matching a query.
118pub const NOT_FOUND: &str = "notFound";
119/// A did:webvh feature this resolver does not support.
120pub const UNSUPPORTED: &str = "unsupported";
121/// The selected version is the deactivated one.
122pub const DEACTIVATED: &str = "deactivated";
123/// A size or count limit.
124pub const TOO_LARGE: &str = "tooLarge";
125/// Fetching took too long (the caller's fetch reports it).
126pub const TIMEOUT: &str = "timeout";
127/// The log could not be fetched (the caller's fetch reports it).
128pub const FETCH_FAILED: &str = "fetchFailed";
129
130/// A did:webvh DID, log or resolution was refused: a stable code, a fixed
131/// text, and the 1-based log line the problem is in when there is one.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct DidWebvhError {
134    /// One of the error codes above.
135    pub code: &'static str,
136    /// The fixed text.
137    pub text: &'static str,
138    /// The 1-based log line, or None.
139    pub entry: Option<usize>,
140    /// For `deactivated`, the versionId of the log's last entry (the log
141    /// itself verified), so a caller can record it; otherwise None.
142    pub latest_version_id: Option<String>,
143}
144
145impl DidWebvhError {
146    fn new(code: &'static str, text: &'static str) -> Self {
147        Self {
148            code,
149            text,
150            entry: None,
151            latest_version_id: None,
152        }
153    }
154
155    fn at(code: &'static str, text: &'static str, entry: usize) -> Self {
156        Self {
157            code,
158            text,
159            entry: Some(entry),
160            latest_version_id: None,
161        }
162    }
163
164    /// `{"code": ..., "text": ..., "entry": n or null}`. The JSON stays the
165    /// shape the shared vectors fix; `latest_version_id` is on the type only.
166    pub fn to_json(&self) -> Value {
167        json!({"code": self.code, "text": self.text, "entry": self.entry})
168    }
169}
170
171impl fmt::Display for DidWebvhError {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.write_str(self.text)
174    }
175}
176
177impl std::error::Error for DidWebvhError {}
178
179/// A result whose error is a did:webvh refusal.
180pub type Refusal<T> = std::result::Result<T, DidWebvhError>;
181
182fn invalid(text: &'static str) -> DidWebvhError {
183    DidWebvhError::new(INVALID_DID, text)
184}
185
186// =============================================================================
187// The DID: syntax and the DID-to-HTTPS transformation (spec 3.3, 3.4)
188// =============================================================================
189
190/// A did:webvh DID, split into its parts.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct DidWebvh {
193    /// The DID, exactly as given.
194    pub did: String,
195    /// The 46-character SCID.
196    pub scid: String,
197    /// The domain, percent-decoded once and lower-cased (the A-label form a
198    /// TLS certificate names).
199    pub host: String,
200    /// The port, or None.
201    pub port: Option<u16>,
202    /// The path segments, each percent-decoded once.
203    pub path: Vec<String>,
204}
205
206impl DidWebvh {
207    /// The HTTPS URL of the DID's log (spec 3.4):
208    /// `https://{host}[:{port}]/{path}/did.jsonl`, or
209    /// `https://{host}[:{port}]/.well-known/did.jsonl` with no path. Each path
210    /// segment is encoded again with uppercase hex.
211    pub fn log_url(&self) -> String {
212        let authority = match self.port {
213            Some(port) => format!("{}:{port}", self.host),
214            None => self.host.clone(),
215        };
216        if self.path.is_empty() {
217            return format!("https://{authority}/.well-known/did.jsonl");
218        }
219        let path: Vec<String> = self.path.iter().map(|s| encode_segment(s)).collect();
220        format!("https://{authority}/{}/did.jsonl", path.join("/"))
221    }
222
223    /// `{"scid", "host", "port", "path", "url"}`.
224    pub fn to_json(&self) -> Value {
225        json!({
226            "scid": self.scid,
227            "host": self.host,
228            "port": self.port,
229            "path": self.path,
230            "url": self.log_url(),
231        })
232    }
233}
234
235fn is_base58_char(c: u8) -> bool {
236    matches!(c, b'1'..=b'9' | b'A'..=b'H' | b'J'..=b'N' | b'P'..=b'Z' | b'a'..=b'k' | b'm'..=b'z')
237}
238
239fn is_scid(text: &str) -> bool {
240    text.len() == 46 && text.bytes().all(is_base58_char)
241}
242
243/// One or more of the characters `allowed` lets through or `%XX` escapes.
244fn escaped_chars_ok(text: &str, allowed: impl Fn(u8) -> bool) -> bool {
245    let b = text.as_bytes();
246    if b.is_empty() {
247        return false;
248    }
249    let mut i = 0;
250    while i < b.len() {
251        if b[i] == b'%' {
252            let hex = |j: usize| b.get(j).is_some_and(u8::is_ascii_hexdigit);
253            if !(hex(i + 1) && hex(i + 2)) {
254                return false;
255            }
256            i += 3;
257        } else if allowed(b[i]) {
258            i += 1;
259        } else {
260            return false;
261        }
262    }
263    true
264}
265
266/// Percent-decode `text` exactly once (every `%` already starts a valid
267/// two-digit escape).
268fn decode_once(text: &str) -> Vec<u8> {
269    let b = text.as_bytes();
270    let mut out = Vec::with_capacity(b.len());
271    let mut i = 0;
272    while i < b.len() {
273        if b[i] == b'%' {
274            let hi = (b[i + 1] as char).to_digit(16).unwrap_or(0) as u8;
275            let lo = (b[i + 2] as char).to_digit(16).unwrap_or(0) as u8;
276            out.push(hi * 16 + lo);
277            i += 3;
278        } else {
279            out.push(b[i]);
280            i += 1;
281        }
282    }
283    out
284}
285
286/// Unicode White_Space, written out so every language uses the same set.
287fn is_listed_whitespace(c: char) -> bool {
288    matches!(
289        c,
290        '\u{09}'..='\u{0D}'
291            | ' '
292            | '\u{85}'
293            | '\u{A0}'
294            | '\u{1680}'
295            | '\u{2000}'..='\u{200A}'
296            | '\u{2028}'
297            | '\u{2029}'
298            | '\u{202F}'
299            | '\u{205F}'
300            | '\u{3000}'
301    )
302}
303
304/// The host and port of the domain component (spec 3.3, "webvh-domain").
305fn parse_domain(component: &str) -> Refusal<(String, Option<u16>)> {
306    if !escaped_chars_ok(component, |c| {
307        c.is_ascii_alphanumeric() || c == b'.' || c == b'-'
308    }) {
309        return Err(invalid(
310            "the domain holds a character a did:webvh domain cannot",
311        ));
312    }
313    let b = component.as_bytes();
314    let mut colons = Vec::new();
315    let mut i = 0;
316    while i < b.len() {
317        if b[i] == b'%' {
318            if b[i + 1..i + 3].eq_ignore_ascii_case(b"3a") {
319                colons.push(i);
320            }
321            i += 3;
322        } else {
323            i += 1;
324        }
325    }
326    if colons.len() > 1 {
327        return Err(invalid("the domain has more than one port separator"));
328    }
329    let mut host_part = component;
330    let mut port = None;
331    if let Some(&at) = colons.first() {
332        let port_text = &component[at + 3..];
333        if port_text.is_empty() || !port_text.bytes().all(|c| c.is_ascii_digit()) {
334            return Err(invalid(
335                "a percent-encoded colon may only come before the port",
336            ));
337        }
338        let value: u32 = if port_text.len() <= 5 && !port_text.starts_with('0') {
339            port_text.parse().unwrap_or(u32::MAX)
340        } else {
341            u32::MAX
342        };
343        if value > 65535 {
344            return Err(invalid("the port must be 1 to 65535, with no leading zero"));
345        }
346        port = Some(value as u16);
347        host_part = &component[..at];
348    }
349    if host_part.split('.').any(str::is_empty) {
350        return Err(invalid("a did:webvh domain label is empty"));
351    }
352    if host_part.split('.').count() < 2 {
353        return Err(invalid("a did:webvh domain needs at least two labels"));
354    }
355    let decoded = decode_once(host_part);
356    if decoded.iter().any(|c| *c >= 0x80) {
357        if std::str::from_utf8(&decoded).is_err() {
358            return Err(invalid("the domain does not decode to UTF-8 text"));
359        }
360        return Err(DidWebvhError::new(
361            UNSUPPORTED,
362            "internationalized domains must be written in their A-label (xn--) form",
363        ));
364    }
365    // ASCII, so this never fails.
366    let host = String::from_utf8(decoded).unwrap_or_default();
367    let labels: Vec<&str> = host.split('.').collect();
368    if labels.iter().any(|l| l.is_empty()) {
369        return Err(invalid("a did:webvh domain label is empty"));
370    }
371    if !labels.iter().all(|l| crate::did_web::is_ldh_label(l)) {
372        return Err(invalid(
373            "a domain label must be 1 to 63 letters, digits or hyphens, \
374             not starting or ending with a hyphen",
375        ));
376    }
377    if host.len() > 253 {
378        return Err(invalid("the domain is longer than 253 characters"));
379    }
380    let last = labels[labels.len() - 1];
381    let hex_label = last.len() >= 2
382        && (last.starts_with("0x") || last.starts_with("0X"))
383        && last[2..].bytes().all(|c| c.is_ascii_hexdigit());
384    if last.bytes().all(|c| c.is_ascii_digit())
385        || hex_label
386        || crate::did_web::is_inet_aton_address(&host)
387    {
388        return Err(invalid("the domain is an IP address, not a domain name"));
389    }
390    if last.eq_ignore_ascii_case("localhost") {
391        return Err(invalid("localhost is not a did:webvh domain"));
392    }
393    Ok((host.to_ascii_lowercase(), port))
394}
395
396/// One path segment, percent-decoded once (spec 3.3, "webvh-path-segment").
397fn parse_segment(segment: &str) -> Refusal<String> {
398    if segment.is_empty() {
399        return Err(invalid("a did:webvh path segment is empty"));
400    }
401    if !escaped_chars_ok(segment, |c| {
402        c.is_ascii_alphanumeric() || c == b'.' || c == b'_' || c == b'-'
403    }) {
404        return Err(invalid(
405            "a did:webvh path segment holds a character it cannot",
406        ));
407    }
408    let decoded = String::from_utf8(decode_once(segment))
409        .map_err(|_| invalid("a did:webvh path segment does not decode to UTF-8 text"))?;
410    if decoded == "." || decoded == ".." {
411        return Err(invalid("a did:webvh path segment is . or .."));
412    }
413    if decoded
414        .chars()
415        .any(|c| c == '/' || c == '\\' || (c as u32) < 0x20 || c as u32 == 0x7F)
416    {
417        return Err(invalid(
418            "a did:webvh path segment holds /, \\ or a control character",
419        ));
420    }
421    let first = decoded.chars().next().unwrap_or('x');
422    let last = decoded.chars().next_back().unwrap_or('x');
423    if is_listed_whitespace(first) || is_listed_whitespace(last) {
424        return Err(invalid(
425            "a did:webvh path segment begins or ends with whitespace",
426        ));
427    }
428    Ok(decoded)
429}
430
431/// Split a did:webvh DID into its parts, strictly (spec 3.3).
432///
433/// The rules, all checked before anything is fetched:
434///
435/// - the DID starts with `did:webvh:`; the SCID is exactly 46 base58btc
436///   characters (so the `{SCID}` placeholder never parses);
437/// - the domain is letters, digits, hyphens, dots and `%XX` escapes. A `%3A`
438///   (either case) followed by 1 to 5 digits at its end is the port, 1 to
439///   65535 with no leading zero; any other `%3A` is refused. It is
440///   percent-decoded once, must be ASCII (a U-label is `unsupported`), and
441///   must then be two or more LDH labels of 1 to 63 characters, at most 253
442///   characters in all, not an IP address in any form `inet_aton` or a URL
443///   parser reads, and not `localhost` or a name under it;
444/// - every path segment is letters, digits, `.`, `-`, `_` and `%XX` escapes,
445///   decoded once to UTF-8 text that is not `.` or `..`, holds no `/`, `\`
446///   or control character, and does not begin or end with whitespace;
447/// - a DID URL (anything after `/`, `?` or `#`) is refused as `unsupported`,
448///   after the DID before it has been checked.
449pub fn parse(did: &str) -> Refusal<DidWebvh> {
450    if !did.starts_with(PREFIX) {
451        return Err(invalid("not a did:webvh DID"));
452    }
453    let cut = did.find(['/', '?', '#']).unwrap_or(did.len());
454    let (bare, suffix) = did.split_at(cut);
455    let parts: Vec<&str> = bare[PREFIX.len()..].split(':').collect();
456    if !is_scid(parts[0]) {
457        return Err(invalid("the SCID is not 46 base58btc characters"));
458    }
459    if parts.len() < 2 {
460        return Err(invalid("a did:webvh DID needs a domain after the SCID"));
461    }
462    let (host, port) = parse_domain(parts[1])?;
463    let path = parts[2..]
464        .iter()
465        .map(|s| parse_segment(s))
466        .collect::<Refusal<Vec<String>>>()?;
467    if !suffix.is_empty() {
468        return Err(DidWebvhError::new(
469            UNSUPPORTED,
470            "did:webvh DID URLs (a path, query or fragment) are not supported",
471        ));
472    }
473    Ok(DidWebvh {
474        did: bare.to_string(),
475        scid: parts[0].to_string(),
476        host,
477        port,
478        path,
479    })
480}
481
482/// True when `did` starts with `did:webvh:`.
483pub fn is_did_webvh(did: &str) -> bool {
484    did.starts_with(PREFIX)
485}
486
487/// Percent-encode a decoded path segment for a URL (RFC 3986): unreserved
488/// characters stay as they are, every other byte becomes uppercase `%XX`.
489fn encode_segment(segment: &str) -> String {
490    let mut out = String::with_capacity(segment.len());
491    for b in segment.bytes() {
492        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
493            out.push(b as char);
494        } else {
495            out.push_str(&format!("%{b:02X}"));
496        }
497    }
498    out
499}
500
501/// The HTTPS URL of a did:webvh DID's log (spec 3.4); see
502/// [`DidWebvh::log_url`].
503pub fn log_url(did: &str) -> Refusal<String> {
504    Ok(parse(did)?.log_url())
505}
506
507// =============================================================================
508// Limits, options and results
509// =============================================================================
510
511/// Size and count limits for one log. Each may be lowered; none may be
512/// raised past its default, except `max_bytes`, which goes up to 5 MiB.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub struct Limits {
515    max_bytes: usize,
516    max_entries: usize,
517    max_line_bytes: usize,
518    max_proofs: usize,
519    max_update_keys: usize,
520    max_next_key_hashes: usize,
521}
522
523impl Default for Limits {
524    fn default() -> Self {
525        Self {
526            max_bytes: 1024 * 1024,
527            max_entries: 1000,
528            max_line_bytes: 128 * 1024,
529            max_proofs: 4,
530            max_update_keys: 32,
531            max_next_key_hashes: 32,
532        }
533    }
534}
535
536const LIMIT_NAMES: [&str; 6] = [
537    "maxBytes",
538    "maxEntries",
539    "maxLineBytes",
540    "maxProofs",
541    "maxUpdateKeys",
542    "maxNextKeyHashes",
543];
544
545impl Limits {
546    /// Limits with every value given: each at least 1, `max_bytes` at most
547    /// 5 MiB, `max_entries` at most 1000, `max_proofs` at most 4, and
548    /// `max_update_keys` and `max_next_key_hashes` at most 32.
549    pub fn new(
550        max_bytes: usize,
551        max_entries: usize,
552        max_line_bytes: usize,
553        max_proofs: usize,
554        max_update_keys: usize,
555        max_next_key_hashes: usize,
556    ) -> Result<Self> {
557        let values = [
558            max_bytes,
559            max_entries,
560            max_line_bytes,
561            max_proofs,
562            max_update_keys,
563            max_next_key_hashes,
564        ];
565        for (name, value) in LIMIT_NAMES.iter().zip(values) {
566            if value < 1 {
567                return Err(CoreError::Json(format!(
568                    "{name} must be a positive whole number"
569                )));
570            }
571        }
572        if max_bytes > HARD_MAX_BYTES {
573            return Err(CoreError::Json(format!(
574                "maxBytes may be at most {HARD_MAX_BYTES} (5 MiB)"
575            )));
576        }
577        for (name, value, most) in [
578            ("maxEntries", max_entries, HARD_MAX_ENTRIES),
579            ("maxProofs", max_proofs, HARD_MAX_PROOFS),
580            ("maxUpdateKeys", max_update_keys, HARD_MAX_UPDATE_KEYS),
581            (
582                "maxNextKeyHashes",
583                max_next_key_hashes,
584                HARD_MAX_NEXT_KEY_HASHES,
585            ),
586        ] {
587            if value > most {
588                return Err(CoreError::Json(format!("{name} may be at most {most}")));
589            }
590        }
591        Ok(Self {
592            max_bytes,
593            max_entries,
594            max_line_bytes,
595            max_proofs,
596            max_update_keys,
597            max_next_key_hashes,
598        })
599    }
600
601    /// Limits from a JSON object with any of `maxBytes`, `maxEntries`,
602    /// `maxLineBytes`, `maxProofs`, `maxUpdateKeys` and `maxNextKeyHashes`;
603    /// the rest keep their defaults.
604    pub fn from_json(value: &Value) -> Result<Self> {
605        let obj = value
606            .as_object()
607            .ok_or_else(|| CoreError::Json("limits must be a JSON object".into()))?;
608        if let Some(name) = obj.keys().find(|k| !LIMIT_NAMES.contains(&k.as_str())) {
609            return Err(CoreError::Json(format!(
610                "limits holds an unknown member {:?}",
611                name.chars().take(40).collect::<String>()
612            )));
613        }
614        let d = Self::default();
615        let defaults = [
616            d.max_bytes,
617            d.max_entries,
618            d.max_line_bytes,
619            d.max_proofs,
620            d.max_update_keys,
621            d.max_next_key_hashes,
622        ];
623        let mut values = [0usize; 6];
624        for (i, name) in LIMIT_NAMES.iter().enumerate() {
625            values[i] = match obj.get(*name) {
626                None => defaults[i],
627                Some(v) => v
628                    .as_u64()
629                    .and_then(|n| usize::try_from(n).ok())
630                    .filter(|n| *n >= 1)
631                    .ok_or_else(|| {
632                        CoreError::Json(format!("{name} must be a positive whole number"))
633                    })?,
634            };
635        }
636        Self::new(
637            values[0], values[1], values[2], values[3], values[4], values[5],
638        )
639    }
640
641    /// The largest log, in bytes.
642    pub fn max_bytes(&self) -> usize {
643        self.max_bytes
644    }
645    /// The most entries.
646    pub fn max_entries(&self) -> usize {
647        self.max_entries
648    }
649    /// The longest line, in bytes, without its newline.
650    pub fn max_line_bytes(&self) -> usize {
651        self.max_line_bytes
652    }
653    /// The most proofs on one entry.
654    pub fn max_proofs(&self) -> usize {
655        self.max_proofs
656    }
657    /// The most keys in one `updateKeys`.
658    pub fn max_update_keys(&self) -> usize {
659        self.max_update_keys
660    }
661    /// The most hashes in one `nextKeyHashes`.
662    pub fn max_next_key_hashes(&self) -> usize {
663        self.max_next_key_hashes
664    }
665}
666
667/// Which version of the log to resolve.
668#[derive(Debug, Clone, PartialEq, Eq, Default)]
669pub enum Query {
670    /// The last entry (what credential verification always uses).
671    #[default]
672    Latest,
673    /// The entry with exactly this versionId.
674    VersionId(String),
675    /// The entry active at this protocol time: the last entry whose
676    /// versionTime is at or before it.
677    VersionTime(String),
678    /// The entry with this version number (1 is the first).
679    VersionNumber(i64),
680}
681
682/// The options for [`verify_log`]: a version query, the versionId seen
683/// before for this DID, and the limits.
684#[derive(Debug, Clone, Default, PartialEq, Eq)]
685pub struct VerifyOptions {
686    query: Query,
687    seen_version_id: Option<String>,
688    limits: Limits,
689}
690
691/// The version number of a versionId ("3-Qm..." is 3), when it has one.
692fn version_number_of(version_id: &str) -> Option<usize> {
693    let (head, _) = version_id.split_once('-')?;
694    let b = head.as_bytes();
695    if b.is_empty() || b.len() > 9 || !(b'1'..=b'9').contains(&b[0]) {
696        return None;
697    }
698    if !b.iter().all(u8::is_ascii_digit) {
699        return None;
700    }
701    head.parse().ok()
702}
703
704impl VerifyOptions {
705    /// The latest version, no version seen before, default limits.
706    pub fn new() -> Self {
707        Self::default()
708    }
709
710    /// Resolve the version `query` names.
711    pub fn with_query(mut self, query: Query) -> Self {
712        self.query = query;
713        self
714    }
715
716    /// Use these limits.
717    pub fn with_limits(mut self, limits: Limits) -> Self {
718        self.limits = limits;
719        self
720    }
721
722    /// The latest versionId seen for this DID before. The log must still
723    /// contain it, so a log rolled back or forked since is refused.
724    ///
725    /// Errors when `seen` is not a did:webvh versionId.
726    pub fn with_seen_version_id(mut self, seen: &str) -> Result<Self> {
727        if version_number_of(seen).is_none() {
728            return Err(seen_version_id_error());
729        }
730        self.seen_version_id = Some(seen.to_string());
731        Ok(self)
732    }
733
734    /// The version query.
735    pub fn query(&self) -> &Query {
736        &self.query
737    }
738    /// The versionId seen before, if any.
739    pub fn seen_version_id(&self) -> Option<&str> {
740        self.seen_version_id.as_deref()
741    }
742    /// The limits.
743    pub fn limits(&self) -> &Limits {
744        &self.limits
745    }
746
747    /// Options from a JSON object with at most one of `versionId` (a
748    /// string), `versionTime` (a string) and `versionNumber` (a whole
749    /// number), and optionally `seenVersionId` and `limits` (see
750    /// [`Limits::from_json`]). A null member counts as absent.
751    pub fn from_json(value: &Value) -> Result<Self> {
752        let obj = value
753            .as_object()
754            .ok_or_else(|| CoreError::Json("options must be a JSON object".into()))?;
755        let (query, seen) = read_query(obj)?;
756        let mut options = Self::new().with_query(query);
757        if let Some(seen) = seen {
758            options = options.with_seen_version_id(&seen)?;
759        }
760        if let Some(v) = obj.get("limits").filter(|v| !v.is_null()) {
761            options.limits = Limits::from_json(v)?;
762        }
763        Ok(options)
764    }
765}
766
767/// The query and the version seen before in an options object, read in the
768/// reference's order: unknown members, at most one query, then each type. A
769/// null member counts as absent. The seen versionId is only checked to be
770/// text here; whether it is a versionId is checked by the caller.
771fn read_query(obj: &Map<String, Value>) -> Result<(Query, Option<String>)> {
772    const NAMES: [&str; 5] = [
773        "versionId",
774        "versionTime",
775        "versionNumber",
776        "seenVersionId",
777        "limits",
778    ];
779    if let Some(name) = obj.keys().find(|k| !NAMES.contains(&k.as_str())) {
780        return Err(CoreError::Json(format!(
781            "options holds an unknown member {:?}",
782            name.chars().take(40).collect::<String>()
783        )));
784    }
785    let present = |name: &str| obj.get(name).filter(|v| !v.is_null());
786    let queries = ["versionId", "versionTime", "versionNumber"]
787        .iter()
788        .filter(|n| present(n).is_some())
789        .count();
790    if queries > 1 {
791        return Err(CoreError::Json(
792            "give at most one of versionId, versionTime and versionNumber".into(),
793        ));
794    }
795    let text = |name: &str, v: &Value| {
796        v.as_str()
797            .map(str::to_string)
798            .ok_or_else(|| CoreError::Json(format!("{name} must be a string")))
799    };
800    let mut query = Query::Latest;
801    if let Some(v) = present("versionId") {
802        query = Query::VersionId(text("versionId", v)?);
803    }
804    if let Some(v) = present("versionTime") {
805        query = Query::VersionTime(text("versionTime", v)?);
806    }
807    if let Some(v) = present("versionNumber") {
808        let n = match v {
809            Value::Number(n) if n.is_i64() => n.as_i64().unwrap_or(i64::MAX),
810            // A whole number beyond i64 names no entry either way.
811            Value::Number(n) if n.is_u64() => i64::MAX,
812            _ => {
813                return Err(CoreError::Json(
814                    "versionNumber must be a whole number".into(),
815                ))
816            }
817        };
818        query = Query::VersionNumber(n);
819    }
820    let seen = match present("seenVersionId") {
821        Some(v) => Some(text("seenVersionId", v)?),
822        None => None,
823    };
824    Ok((query, seen))
825}
826
827fn seen_version_id_error() -> CoreError {
828    CoreError::Json("seenVersionId is not a did:webvh versionId".into())
829}
830
831/// A verified did:webvh log, resolved to one version.
832#[derive(Debug, Clone, PartialEq)]
833pub struct Resolution {
834    /// The selected entry's `state`, exactly as the log holds it: the DID
835    /// document. Its `id` is exactly the DID.
836    pub document: Value,
837    /// The DID document metadata (spec 3.6.2): `versionId`, `versionTime`
838    /// (of the selected entry), `created` and `updated` (the first and last
839    /// entries' times), `scid`, `portable`, `deactivated`, `ttl` (a string),
840    /// `witness` and `watchers` (active after the last entry).
841    pub metadata: Value,
842    /// The selected entry's version number.
843    pub version_number: usize,
844    /// The versionId of the log's last entry, to remember so a later,
845    /// shorter log can be refused.
846    pub latest_version_id: String,
847}
848
849impl Resolution {
850    /// `{"document", "metadata", "versionNumber", "latestVersionId"}`.
851    pub fn to_json(&self) -> Value {
852        json!({
853            "document": self.document,
854            "metadata": self.metadata,
855            "versionNumber": self.version_number,
856            "latestVersionId": self.latest_version_id,
857        })
858    }
859}
860
861// =============================================================================
862// Reading the log (step 1 of the check order)
863// =============================================================================
864
865const ENTRY_MEMBERS: [&str; 5] = ["versionId", "versionTime", "parameters", "state", "proof"];
866const PROOF_MEMBERS: [&str; 6] = [
867    "type",
868    "cryptosuite",
869    "verificationMethod",
870    "created",
871    "proofPurpose",
872    "proofValue",
873];
874const PROOF_REQUIRED: [&str; 5] = [
875    "type",
876    "cryptosuite",
877    "verificationMethod",
878    "proofPurpose",
879    "proofValue",
880];
881const PARAMETERS: [&str; 9] = [
882    "method",
883    "scid",
884    "updateKeys",
885    "nextKeyHashes",
886    "witness",
887    "watchers",
888    "portable",
889    "deactivated",
890    "ttl",
891];
892
893/// Whether JSON text nests objects and lists more than `limit` deep: one scan
894/// of the raw bytes, before parsing. Every `[` or `{` outside a string adds a
895/// level and every `]` or `}` takes one away (escapes inside strings are
896/// honoured, and a string with no closing quote runs to the end), so the
897/// answer does not depend on what else is wrong with the text.
898fn json_too_deep(text: &[u8], limit: usize) -> bool {
899    let mut depth: i64 = 0;
900    let mut i = 0;
901    while i < text.len() {
902        match text[i] {
903            b'"' => {
904                i += 1;
905                while i < text.len() {
906                    match text[i] {
907                        b'"' => {
908                            i += 1;
909                            break;
910                        }
911                        b'\\' if i + 1 < text.len() => i += 2,
912                        b'\\' => break,
913                        _ => i += 1,
914                    }
915                }
916                continue;
917            }
918            b'[' | b'{' => {
919                depth += 1;
920                if depth > limit as i64 {
921                    return true;
922                }
923            }
924            b']' | b'}' => depth -= 1,
925            _ => {}
926        }
927        i += 1;
928    }
929    false
930}
931
932/// Why a log line could not be read as JSON.
933#[derive(Debug, Clone, Copy, PartialEq, Eq)]
934enum JsonProblem {
935    Repeated,
936    OutOfRange,
937    Invalid,
938}
939
940/// A guard for the reader's recursion; the bracket scan keeps every line it
941/// reads far below it.
942const MAX_READER_DEPTH: usize = 256;
943
944/// A strict JSON reader for one log line. It reads the same grammar as
945/// Python's `json` module (the reference's reader) and reports a problem at
946/// the same point: a number when it is read, a repeated member name when its
947/// object closes, anything else not JSON where it occurs. A lone surrogate is
948/// remembered and reported by the caller after the whole line is read.
949struct LineReader<'a> {
950    b: &'a [u8],
951    i: usize,
952    lone_surrogate: bool,
953}
954
955impl<'a> LineReader<'a> {
956    fn skip_ws(&mut self) {
957        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\n' | b'\r') {
958            self.i += 1;
959        }
960    }
961
962    fn peek(&self) -> Option<u8> {
963        self.b.get(self.i).copied()
964    }
965
966    fn literal(&mut self, word: &[u8], value: Value) -> std::result::Result<Value, JsonProblem> {
967        if self.b[self.i..].starts_with(word) {
968            self.i += word.len();
969            Ok(value)
970        } else {
971            Err(JsonProblem::Invalid)
972        }
973    }
974
975    fn value(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
976        if depth > MAX_READER_DEPTH {
977            return Err(JsonProblem::Invalid);
978        }
979        match self.peek() {
980            Some(b'"') => {
981                self.i += 1;
982                Ok(Value::String(self.string()?.0))
983            }
984            Some(b'{') => self.object(depth + 1),
985            Some(b'[') => self.array(depth + 1),
986            Some(b'n') => self.literal(b"null", Value::Null),
987            Some(b't') => self.literal(b"true", Value::Bool(true)),
988            Some(b'f') => self.literal(b"false", Value::Bool(false)),
989            Some(_) => self.number(),
990            None => Err(JsonProblem::Invalid),
991        }
992    }
993
994    fn object(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
995        self.i += 1; // '{'
996        let mut map = Map::new();
997        let mut names: HashSet<Vec<u16>> = HashSet::new();
998        let mut repeated = false;
999        self.skip_ws();
1000        if self.peek() == Some(b'}') {
1001            self.i += 1;
1002            return Ok(Value::Object(map));
1003        }
1004        loop {
1005            if self.peek() != Some(b'"') {
1006                return Err(JsonProblem::Invalid);
1007            }
1008            self.i += 1;
1009            let (name, units) = self.string()?;
1010            self.skip_ws();
1011            if self.peek() != Some(b':') {
1012                return Err(JsonProblem::Invalid);
1013            }
1014            self.i += 1;
1015            self.skip_ws();
1016            let value = self.value(depth)?;
1017            if !names.insert(units) {
1018                repeated = true;
1019            }
1020            map.insert(name, value);
1021            self.skip_ws();
1022            match self.peek() {
1023                Some(b'}') => {
1024                    self.i += 1;
1025                    break;
1026                }
1027                Some(b',') => {
1028                    self.i += 1;
1029                    self.skip_ws();
1030                }
1031                _ => return Err(JsonProblem::Invalid),
1032            }
1033        }
1034        // The reference checks member names when the object closes.
1035        if repeated {
1036            return Err(JsonProblem::Repeated);
1037        }
1038        Ok(Value::Object(map))
1039    }
1040
1041    fn array(&mut self, depth: usize) -> std::result::Result<Value, JsonProblem> {
1042        self.i += 1; // '['
1043        let mut items = Vec::new();
1044        self.skip_ws();
1045        if self.peek() == Some(b']') {
1046            self.i += 1;
1047            return Ok(Value::Array(items));
1048        }
1049        loop {
1050            items.push(self.value(depth)?);
1051            self.skip_ws();
1052            match self.peek() {
1053                Some(b']') => {
1054                    self.i += 1;
1055                    break;
1056                }
1057                Some(b',') => {
1058                    self.i += 1;
1059                    self.skip_ws();
1060                }
1061                _ => return Err(JsonProblem::Invalid),
1062            }
1063        }
1064        Ok(Value::Array(items))
1065    }
1066
1067    /// A number, matched the way Python's scanner matches one (an integer
1068    /// part, then a fraction only when a digit follows the dot, then an
1069    /// exponent only when it has digits), and range-checked at once.
1070    fn number(&mut self) -> std::result::Result<Value, JsonProblem> {
1071        let b = self.b;
1072        let n = b.len();
1073        let start = self.i;
1074        let mut i = start;
1075        let digit = |j: usize| j < n && b[j].is_ascii_digit();
1076        if b[i] == b'-' {
1077            i += 1;
1078            if i >= n {
1079                return Err(JsonProblem::Invalid);
1080            }
1081        }
1082        match b[i] {
1083            b'1'..=b'9' => {
1084                i += 1;
1085                while digit(i) {
1086                    i += 1;
1087                }
1088            }
1089            b'0' => i += 1,
1090            _ => return Err(JsonProblem::Invalid),
1091        }
1092        let mut is_float = false;
1093        if i + 1 < n && b[i] == b'.' && b[i + 1].is_ascii_digit() {
1094            is_float = true;
1095            i += 2;
1096            while digit(i) {
1097                i += 1;
1098            }
1099        }
1100        if i + 1 < n && (b[i] == b'e' || b[i] == b'E') {
1101            let e_start = i;
1102            i += 1;
1103            if i + 1 < n && (b[i] == b'-' || b[i] == b'+') {
1104                i += 1;
1105            }
1106            let digits_start = i;
1107            while digit(i) {
1108                i += 1;
1109            }
1110            if i > digits_start {
1111                is_float = true;
1112            } else {
1113                i = e_start;
1114            }
1115        }
1116        self.i = i;
1117        // ASCII digits and signs only.
1118        let text = std::str::from_utf8(&b[start..i]).map_err(|_| JsonProblem::Invalid)?;
1119        if is_float {
1120            let value: f64 = text.parse().map_err(|_| JsonProblem::Invalid)?;
1121            // Also refuses infinity (1e400).
1122            if !value.is_finite() || value.abs() > MAX_SAFE_INTEGER as f64 {
1123                return Err(JsonProblem::OutOfRange);
1124            }
1125            return Number::from_f64(value)
1126                .map(Value::Number)
1127                .ok_or(JsonProblem::OutOfRange);
1128        }
1129        let digits = text.len() - usize::from(text.starts_with('-'));
1130        if digits > 16 {
1131            // 2^53 - 1 has 16 digits.
1132            return Err(JsonProblem::OutOfRange);
1133        }
1134        let value: i64 = text.parse().map_err(|_| JsonProblem::Invalid)?;
1135        if value.abs() > MAX_SAFE_INTEGER {
1136            return Err(JsonProblem::OutOfRange);
1137        }
1138        Ok(Value::Number(Number::from(value)))
1139    }
1140
1141    /// A string after its opening quote: the text, and its UTF-16 code units
1142    /// (lone surrogates included, so member names compare exactly as the
1143    /// reference compares them).
1144    fn string(&mut self) -> std::result::Result<(String, Vec<u16>), JsonProblem> {
1145        let b = self.b;
1146        let n = b.len();
1147        let mut units: Vec<u16> = Vec::new();
1148        let mut i = self.i;
1149        loop {
1150            let run = i;
1151            while i < n && b[i] != b'"' && b[i] != b'\\' && b[i] >= 0x20 {
1152                i += 1;
1153            }
1154            // The run ends at an ASCII byte, so it is whole UTF-8 text.
1155            let text = std::str::from_utf8(&b[run..i]).map_err(|_| JsonProblem::Invalid)?;
1156            units.extend(text.encode_utf16());
1157            if i >= n {
1158                return Err(JsonProblem::Invalid); // no closing quote
1159            }
1160            match b[i] {
1161                b'"' => {
1162                    i += 1;
1163                    break;
1164                }
1165                b'\\' => {
1166                    let escape = *b.get(i + 1).ok_or(JsonProblem::Invalid)?;
1167                    i += 2;
1168                    let unit = match escape {
1169                        b'"' => 0x22,
1170                        b'\\' => 0x5C,
1171                        b'/' => 0x2F,
1172                        b'b' => 0x08,
1173                        b'f' => 0x0C,
1174                        b'n' => 0x0A,
1175                        b'r' => 0x0D,
1176                        b't' => 0x09,
1177                        b'u' => {
1178                            let hex = b.get(i..i + 4).ok_or(JsonProblem::Invalid)?;
1179                            let mut v: u16 = 0;
1180                            for c in hex {
1181                                let d = (*c as char).to_digit(16).ok_or(JsonProblem::Invalid)?;
1182                                v = v * 16 + d as u16;
1183                            }
1184                            i += 4;
1185                            v
1186                        }
1187                        _ => return Err(JsonProblem::Invalid),
1188                    };
1189                    units.push(unit);
1190                }
1191                // A control character inside a string.
1192                _ => return Err(JsonProblem::Invalid),
1193            }
1194        }
1195        self.i = i;
1196        match String::from_utf16(&units) {
1197            Ok(text) => Ok((text, units)),
1198            Err(_) => {
1199                self.lone_surrogate = true;
1200                Ok((String::from_utf16_lossy(&units), units))
1201            }
1202        }
1203    }
1204}
1205
1206/// One log line as JSON, and whether it held a lone surrogate.
1207fn read_json_line(line: &[u8]) -> std::result::Result<(Value, bool), JsonProblem> {
1208    let mut reader = LineReader {
1209        b: line,
1210        i: 0,
1211        lone_surrogate: false,
1212    };
1213    reader.skip_ws();
1214    let value = reader.value(0)?;
1215    reader.skip_ws();
1216    if reader.i != line.len() {
1217        return Err(JsonProblem::Invalid); // extra data
1218    }
1219    Ok((value, reader.lone_surrogate))
1220}
1221
1222/// One log line as an entry object, checked for shape (step 1).
1223fn read_line(line: &[u8], number: usize, limits: &Limits) -> Refusal<Value> {
1224    let fail = |code, text| DidWebvhError::at(code, text, number);
1225    if line.is_empty() {
1226        return Err(fail(INVALID_DID, "the DID log has a blank line"));
1227    }
1228    if line.len() > limits.max_line_bytes {
1229        return Err(fail(TOO_LARGE, "a DID log line is longer than the limit"));
1230    }
1231    if line.ends_with(b"\r") {
1232        return Err(fail(INVALID_DID, "the DID log uses CRLF line endings"));
1233    }
1234    if line[0] != b'{' || line[line.len() - 1] != b'}' {
1235        return Err(fail(INVALID_DID, "a DID log line is not one JSON object"));
1236    }
1237    if json_too_deep(line, MAX_LOG_DEPTH) {
1238        return Err(fail(INVALID_DID, "a DID log line is nested too deeply"));
1239    }
1240    let (entry, lone_surrogate) = match read_json_line(line) {
1241        Ok(read) => read,
1242        Err(JsonProblem::Repeated) => {
1243            return Err(fail(INVALID_DID, "a DID log line repeats a member name"))
1244        }
1245        Err(JsonProblem::OutOfRange) => return Err(fail(
1246            INVALID_DID,
1247            "a DID log line holds a number beyond 2^53 - 1, which not every reader holds exactly",
1248        )),
1249        Err(JsonProblem::Invalid) => {
1250            return Err(fail(INVALID_DID, "a DID log line is not valid JSON"))
1251        }
1252    };
1253    let Some(obj) = entry.as_object() else {
1254        return Err(fail(INVALID_DID, "a DID log line is not one JSON object"));
1255    };
1256    if lone_surrogate {
1257        return Err(fail(
1258            INVALID_DID,
1259            "a DID log line holds text that is not valid Unicode",
1260        ));
1261    }
1262    if ENTRY_MEMBERS.iter().any(|m| !obj.contains_key(*m)) {
1263        return Err(fail(INVALID_DID, "a DID log entry is missing a member"));
1264    }
1265    if obj.len() != ENTRY_MEMBERS.len() {
1266        return Err(fail(
1267            INVALID_DID,
1268            "a DID log entry has a member did:webvh does not define",
1269        ));
1270    }
1271    if !(obj["versionId"].is_string()
1272        && obj["versionTime"].is_string()
1273        && obj["parameters"].is_object()
1274        && obj["state"].is_object())
1275    {
1276        return Err(fail(
1277            INVALID_DID,
1278            "a DID log entry member has the wrong type",
1279        ));
1280    }
1281    let proofs = match &obj["proof"] {
1282        Value::Array(items) if !items.is_empty() => items,
1283        _ => {
1284            return Err(fail(
1285                INVALID_DID,
1286                "a DID log entry's proof is not a non-empty list",
1287            ))
1288        }
1289    };
1290    if proofs.len() > limits.max_proofs {
1291        return Err(fail(
1292            TOO_LARGE,
1293            "a DID log entry has more proofs than the limit",
1294        ));
1295    }
1296    if !proofs.iter().all(Value::is_object) {
1297        return Err(fail(
1298            INVALID_DID,
1299            "a DID log entry's proof is not a JSON object",
1300        ));
1301    }
1302    Ok(entry)
1303}
1304
1305/// Every entry of a log, read and shape-checked (step 1).
1306fn read_log(log: &[u8], limits: &Limits) -> Refusal<Vec<Value>> {
1307    if log.len() > limits.max_bytes {
1308        return Err(DidWebvhError::new(
1309            TOO_LARGE,
1310            "the DID log is larger than the limit",
1311        ));
1312    }
1313    if log.starts_with(b"\xef\xbb\xbf") {
1314        return Err(invalid("the DID log starts with a byte order mark"));
1315    }
1316    if std::str::from_utf8(log).is_err() {
1317        return Err(invalid("the DID log is not UTF-8 text"));
1318    }
1319    // More than max_entries + 1 pieces always means too many entries, even
1320    // after the final newline's empty piece is dropped.
1321    let mut lines: Vec<&[u8]> = log
1322        .split(|b| *b == b'\n')
1323        .take(limits.max_entries.saturating_add(2))
1324        .collect();
1325    if lines.last().is_some_and(|l| l.is_empty())
1326        && lines.len() <= limits.max_entries.saturating_add(1)
1327    {
1328        lines.pop();
1329    }
1330    if lines.is_empty() {
1331        return Err(invalid("the DID log is empty"));
1332    }
1333    if lines.len() > limits.max_entries {
1334        return Err(DidWebvhError::new(
1335            TOO_LARGE,
1336            "the DID log has more entries than the limit",
1337        ));
1338    }
1339    lines
1340        .iter()
1341        .enumerate()
1342        .map(|(i, line)| read_line(line, i + 1, limits))
1343        .collect()
1344}
1345
1346// =============================================================================
1347// Hashes (spec 3.7.2, 3.7.3, 3.7.6)
1348// =============================================================================
1349
1350/// base58btc(0x12 0x20 || SHA-256(data)): a SHA-256 multihash.
1351fn multihash_b58(data: &[u8]) -> String {
1352    let mut raw = Vec::with_capacity(34);
1353    raw.extend_from_slice(&[0x12, 0x20]);
1354    raw.extend_from_slice(&Sha256::digest(data));
1355    bs58::encode(raw).into_string()
1356}
1357
1358fn jcs_hash(value: &Value) -> String {
1359    multihash_b58(&jcs::canonicalize(value))
1360}
1361
1362fn is_sha256_multihash(text: &str) -> bool {
1363    match multikey::decode_base58_bounded(text) {
1364        Ok(raw) => {
1365            raw.len() == 34 && raw[..2] == [0x12, 0x20] && bs58::encode(&raw).into_string() == text
1366        }
1367        Err(_) => false,
1368    }
1369}
1370
1371/// A pre-rotation hash: base58btc(multihash(UTF-8 of the Multikey)).
1372fn key_hash(key: &str) -> String {
1373    multihash_b58(key.as_bytes())
1374}
1375
1376/// Every member name and every string value in `value`.
1377fn names_and_strings<'a>(value: &'a Value, names: &mut Vec<&'a str>, strings: &mut Vec<&'a str>) {
1378    match value {
1379        Value::String(s) => strings.push(s),
1380        Value::Object(map) => {
1381            for (k, v) in map {
1382                names.push(k);
1383                names_and_strings(v, names, strings);
1384            }
1385        }
1386        Value::Array(items) => {
1387            for v in items {
1388                names_and_strings(v, names, strings);
1389            }
1390        }
1391        _ => {}
1392    }
1393}
1394
1395/// `value` with every occurrence of the SCID in a string replaced by
1396/// `{SCID}` (member names hold no SCID; that was checked).
1397fn with_placeholder(value: &Value, scid: &str) -> Value {
1398    match value {
1399        Value::String(s) => Value::String(s.replace(scid, SCID_PLACEHOLDER)),
1400        Value::Object(map) => Value::Object(
1401            map.iter()
1402                .map(|(k, v)| (k.clone(), with_placeholder(v, scid)))
1403                .collect(),
1404        ),
1405        Value::Array(items) => {
1406            Value::Array(items.iter().map(|v| with_placeholder(v, scid)).collect())
1407        }
1408        other => other.clone(),
1409    }
1410}
1411
1412fn without_proof(entry: &Value) -> Map<String, Value> {
1413    let mut body = entry.as_object().cloned().unwrap_or_default();
1414    body.remove("proof");
1415    body
1416}
1417
1418/// The SCID is the hash of the first entry with the SCID written as `{SCID}`
1419/// (spec 3.7.2). The replacement is done on the parsed strings, so an escaped
1420/// spelling of the SCID is replaced too. A first entry that names the SCID in
1421/// a member name, or holds the literal `{SCID}`, is refused: readers that
1422/// replace text and readers that replace values would hash it differently.
1423fn check_scid(entry: &Value, scid: &str) -> Refusal<()> {
1424    let body = Value::Object(without_proof(entry));
1425    let mut names = Vec::new();
1426    let mut strings = Vec::new();
1427    names_and_strings(&body, &mut names, &mut strings);
1428    if names.iter().any(|k| k.contains(scid)) {
1429        return Err(DidWebvhError::at(
1430            INVALID_DID,
1431            "the first entry uses the SCID in a member name",
1432            1,
1433        ));
1434    }
1435    if names
1436        .iter()
1437        .chain(strings.iter())
1438        .any(|t| t.contains(SCID_PLACEHOLDER))
1439    {
1440        return Err(DidWebvhError::at(
1441            INVALID_DID,
1442            "the first entry holds the literal {SCID}",
1443            1,
1444        ));
1445    }
1446    let mut preliminary = with_placeholder(&body, scid);
1447    if let Some(obj) = preliminary.as_object_mut() {
1448        obj.insert("versionId".into(), Value::String(SCID_PLACEHOLDER.into()));
1449    }
1450    if jcs_hash(&preliminary) != scid {
1451        return Err(DidWebvhError::at(
1452            INVALID_DID,
1453            "the SCID is not the hash of the first entry",
1454            1,
1455        ));
1456    }
1457    Ok(())
1458}
1459
1460// =============================================================================
1461// Verifying the entries (step 2 of the check order)
1462// =============================================================================
1463
1464/// The parameters active after an entry.
1465#[derive(Debug, Clone)]
1466struct Active {
1467    update_keys: Vec<String>,
1468    next_key_hashes: Vec<String>,
1469    watchers: Vec<String>,
1470    portable: bool,
1471    deactivated: bool,
1472    ttl: i64,
1473}
1474
1475impl Active {
1476    fn initial() -> Self {
1477        Self {
1478            update_keys: Vec::new(),
1479            next_key_hashes: Vec::new(),
1480            watchers: Vec::new(),
1481            portable: false,
1482            deactivated: false,
1483            ttl: DEFAULT_TTL,
1484        }
1485    }
1486}
1487
1488/// `(0|[1-9][0-9]{0,8})` as a number.
1489fn method_version_part(text: &str) -> Option<u32> {
1490    let b = text.as_bytes();
1491    if text == "0" {
1492        return Some(0);
1493    }
1494    if b.is_empty()
1495        || b.len() > 9
1496        || !(b'1'..=b'9').contains(&b[0])
1497        || !b.iter().all(u8::is_ascii_digit)
1498    {
1499        return None;
1500    }
1501    text.parse().ok()
1502}
1503
1504fn check_method(value: &Value, number: usize) -> Refusal<()> {
1505    let not_a_version = || {
1506        DidWebvhError::at(
1507            INVALID_DID,
1508            "method is not a did:webvh method version",
1509            number,
1510        )
1511    };
1512    let text = value.as_str().ok_or_else(not_a_version)?;
1513    if text == METHOD {
1514        return Ok(());
1515    }
1516    let version = text.strip_prefix(PREFIX).ok_or_else(not_a_version)?;
1517    let (major, minor) = version.split_once('.').ok_or_else(not_a_version)?;
1518    let (major, minor) = match (method_version_part(major), method_version_part(minor)) {
1519        (Some(a), Some(b)) => (a, b),
1520        _ => return Err(not_a_version()),
1521    };
1522    if number > 1 && (major, minor) < (1, 0) {
1523        return Err(DidWebvhError::at(
1524            INVALID_DID,
1525            "a did:webvh log cannot move to a lower method version",
1526            number,
1527        ));
1528    }
1529    Err(DidWebvhError::at(
1530        UNSUPPORTED,
1531        "only did:webvh:1.0 logs are supported",
1532        number,
1533    ))
1534}
1535
1536fn string_list(value: &Value) -> Option<Vec<&str>> {
1537    value.as_array()?.iter().map(Value::as_str).collect()
1538}
1539
1540fn has_duplicates(items: &[&str]) -> bool {
1541    let mut seen = HashSet::new();
1542    !items.iter().all(|i| seen.insert(*i))
1543}
1544
1545/// A ttl: a whole number (an integral float counts) from 0 to 2^31.
1546fn whole_ttl(value: &Value) -> Option<i64> {
1547    let Value::Number(n) = value else {
1548        return None;
1549    };
1550    let ttl = match n.as_i64() {
1551        Some(i) => i,
1552        None => {
1553            let f = n.as_f64()?;
1554            if f.fract() != 0.0 || !(0.0..=MAX_TTL as f64).contains(&f) {
1555                return None;
1556            }
1557            f as i64
1558        }
1559    };
1560    (0..=MAX_TTL).contains(&ttl).then_some(ttl)
1561}
1562
1563/// Check one entry's parameters and return the parameters active after it
1564/// (spec 3.7.1). The members are checked in a fixed order: unknown names,
1565/// then null, then that the first entry sets method, scid and updateKeys,
1566/// then each parameter in the order of `PARAMETERS`.
1567fn check_parameters(
1568    given: &Map<String, Value>,
1569    active: &Active,
1570    number: usize,
1571    limits: &Limits,
1572) -> Refusal<Active> {
1573    let fail = |code, text| DidWebvhError::at(code, text, number);
1574    if given.keys().any(|k| !PARAMETERS.contains(&k.as_str())) {
1575        return Err(fail(
1576            INVALID_DID,
1577            "the parameters hold a member did:webvh v1.0 does not define",
1578        ));
1579    }
1580    if given.values().any(Value::is_null) {
1581        return Err(fail(INVALID_DID, "a did:webvh parameter is null"));
1582    }
1583    let first = number == 1;
1584    if first {
1585        for (name, text) in [
1586            ("method", "the first entry does not set method"),
1587            ("scid", "the first entry does not set scid"),
1588            ("updateKeys", "the first entry does not set updateKeys"),
1589        ] {
1590            if !given.contains_key(name) {
1591                return Err(fail(INVALID_DID, text));
1592            }
1593        }
1594    }
1595
1596    if let Some(method) = given.get("method") {
1597        check_method(method, number)?;
1598    }
1599    if let Some(scid) = given.get("scid") {
1600        if !first {
1601            return Err(fail(INVALID_DID, "only the first entry may set scid"));
1602        }
1603        if !scid.as_str().is_some_and(is_scid) {
1604            return Err(fail(INVALID_DID, "scid is not 46 base58btc characters"));
1605        }
1606    }
1607    if let Some(value) = given.get("updateKeys") {
1608        let keys = string_list(value)
1609            .ok_or_else(|| fail(INVALID_DID, "updateKeys must be a list of Multikey strings"))?;
1610        if keys.len() > limits.max_update_keys {
1611            return Err(fail(TOO_LARGE, "updateKeys holds more keys than the limit"));
1612        }
1613        for key in &keys {
1614            if !multikey::decode(key).is_ok_and(|d| d.algorithm == "Ed25519") {
1615                return Err(fail(
1616                    INVALID_DID,
1617                    "an updateKeys entry is not an Ed25519 Multikey",
1618                ));
1619            }
1620        }
1621        if has_duplicates(&keys) {
1622            return Err(fail(INVALID_DID, "updateKeys lists a key twice"));
1623        }
1624    }
1625    if let Some(value) = given.get("nextKeyHashes") {
1626        let hashes = string_list(value)
1627            .ok_or_else(|| fail(INVALID_DID, "nextKeyHashes must be a list of strings"))?;
1628        if hashes.len() > limits.max_next_key_hashes {
1629            return Err(fail(
1630                TOO_LARGE,
1631                "nextKeyHashes holds more hashes than the limit",
1632            ));
1633        }
1634        if has_duplicates(&hashes) {
1635            return Err(fail(INVALID_DID, "nextKeyHashes lists a hash twice"));
1636        }
1637    }
1638    if let Some(value) = given.get("witness") {
1639        let witness = value
1640            .as_object()
1641            .ok_or_else(|| fail(INVALID_DID, "witness must be a JSON object"))?;
1642        if !witness.is_empty() {
1643            return Err(fail(UNSUPPORTED, "did:webvh witnesses are not supported"));
1644        }
1645    }
1646    if let Some(value) = given.get("watchers") {
1647        let watchers = string_list(value)
1648            .ok_or_else(|| fail(INVALID_DID, "watchers must be a list of strings"))?;
1649        if has_duplicates(&watchers) {
1650            return Err(fail(INVALID_DID, "watchers lists a URL twice"));
1651        }
1652    }
1653    if let Some(value) = given.get("portable") {
1654        let portable = value
1655            .as_bool()
1656            .ok_or_else(|| fail(INVALID_DID, "portable must be true or false"))?;
1657        if portable && !first {
1658            return Err(fail(
1659                INVALID_DID,
1660                "only the first entry may set portable to true",
1661            ));
1662        }
1663    }
1664    if given.get("deactivated").is_some_and(|v| !v.is_boolean()) {
1665        return Err(fail(INVALID_DID, "deactivated must be true or false"));
1666    }
1667    let ttl = match given.get("ttl") {
1668        Some(value) => Some(whole_ttl(value).ok_or_else(|| {
1669            fail(
1670                INVALID_DID,
1671                "ttl must be a whole number of seconds from 0 to 2^31",
1672            )
1673        })?),
1674        None => None,
1675    };
1676
1677    let mut after = if first {
1678        Active::initial()
1679    } else {
1680        active.clone()
1681    };
1682    let owned = |v: &Value| -> Vec<String> {
1683        string_list(v)
1684            .unwrap_or_default()
1685            .into_iter()
1686            .map(str::to_string)
1687            .collect()
1688    };
1689    if let Some(v) = given.get("updateKeys") {
1690        after.update_keys = owned(v);
1691    }
1692    if let Some(v) = given.get("nextKeyHashes") {
1693        after.next_key_hashes = owned(v);
1694    }
1695    if let Some(v) = given.get("watchers") {
1696        after.watchers = owned(v);
1697    }
1698    if let Some(v) = given.get("portable").and_then(Value::as_bool) {
1699        after.portable = v;
1700    }
1701    if let Some(v) = given.get("deactivated").and_then(Value::as_bool) {
1702        after.deactivated = v;
1703    }
1704    if let Some(ttl) = ttl {
1705        after.ttl = ttl;
1706    }
1707    Ok(after)
1708}
1709
1710/// The Multikey a log proof's `did:key:<key>#<key>` names (spec 3.7.4,
1711/// 3.7.8: the body and the fragment must be the same).
1712fn proof_key(verification_method: Option<&Value>, number: usize) -> Refusal<String> {
1713    let shape = || {
1714        DidWebvhError::at(
1715            INVALID_DID,
1716            "a log entry proof's verificationMethod must be did:key:<key>#<key>",
1717            number,
1718        )
1719    };
1720    let rest = verification_method
1721        .and_then(Value::as_str)
1722        .and_then(|vm| vm.strip_prefix("did:key:"))
1723        .ok_or_else(shape)?;
1724    let (body, fragment) = rest.split_once('#').ok_or_else(shape)?;
1725    if body != fragment {
1726        return Err(shape());
1727    }
1728    if !multikey::decode(body).is_ok_and(|d| d.algorithm == "Ed25519") {
1729        return Err(DidWebvhError::at(
1730            INVALID_DID,
1731            "a log entry proof's key is not an Ed25519 Multikey",
1732            number,
1733        ));
1734    }
1735    Ok(body.to_string())
1736}
1737
1738/// The group order L, little-endian.
1739const GROUP_ORDER_LE: [u8; 32] = [
1740    0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
1741    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
1742];
1743
1744/// Every encoding of a small-order Ed25519 point (the 8 torsion points, with
1745/// their sign-bit and y >= p spellings): the fixed set the reference refuses
1746/// as a signature's R.
1747const SMALL_ORDER_ENCODINGS: [&str; 14] = [
1748    "0000000000000000000000000000000000000000000000000000000000000000",
1749    "0000000000000000000000000000000000000000000000000000000000000080",
1750    "0100000000000000000000000000000000000000000000000000000000000000",
1751    "0100000000000000000000000000000000000000000000000000000000000080",
1752    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
1753    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
1754    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
1755    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
1756    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1757    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1758    "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1759    "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1760    "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1761    "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1762];
1763
1764/// The 64-byte Ed25519 signature in an eddsa-jcs-2022 proofValue, checked
1765/// for its form before it is used, exactly as the reference checks it:
1766/// multibase base58btc ("z") of exactly 64 bytes, an R whose y is below p
1767/// and that is not one of the small-order encodings, and an S below the
1768/// group order. None for anything else. Whether R is a point on the curve is
1769/// not checked here: an R off the curve fails at verification ("does not
1770/// verify"), as in the reference.
1771fn strict_signature(proof_value: &Value) -> Option<Vec<u8>> {
1772    let body = proof_value.as_str()?.strip_prefix('z')?;
1773    let signature = multikey::decode_base58_bounded(body).ok()?;
1774    if signature.len() != keys::ED25519_SIGNATURE_LEN {
1775        return None;
1776    }
1777    let mut r = [0u8; 32];
1778    r.copy_from_slice(&signature[..32]);
1779    if !keys::is_canonical_point_encoding(&r) {
1780        return None;
1781    }
1782    let r_hex: String = r.iter().map(|b| format!("{b:02x}")).collect();
1783    if SMALL_ORDER_ENCODINGS.contains(&r_hex.as_str()) {
1784        return None;
1785    }
1786    // S < L, compared as little-endian numbers from the top byte down.
1787    let s = &signature[32..];
1788    for i in (0..32).rev() {
1789        if s[i] != GROUP_ORDER_LE[i] {
1790            return (s[i] < GROUP_ORDER_LE[i]).then_some(signature);
1791        }
1792    }
1793    None // S == L
1794}
1795
1796/// Every proof on the entry is a valid eddsa-jcs-2022 proof by an
1797/// authorized update key (spec 3.6.2 step 2, 3.7.4). The signing input is
1798/// [`crate::data_integrity::hash_data`]'s: SHA-256 of the JCS proof configuration
1799/// (the proof without proofValue) joined with SHA-256 of the JCS entry
1800/// without its proof. The entry's half is computed once and shared by every
1801/// proof. The key and the signature are checked with the strict Ed25519
1802/// rules.
1803fn check_proofs(entry: &Value, authorized: &[String], number: usize) -> Refusal<()> {
1804    let fail = |text| DidWebvhError::at(INVALID_DID, text, number);
1805    let proofs: &[Value] = entry["proof"].as_array().map_or(&[], Vec::as_slice);
1806    let document = Value::Object(without_proof(entry));
1807    let mut document_hash: Option<[u8; 32]> = None;
1808    for proof in proofs {
1809        let Some(p) = proof.as_object() else {
1810            return Err(fail("a log entry proof is missing a member"));
1811        };
1812        if p.keys().any(|k| !PROOF_MEMBERS.contains(&k.as_str())) {
1813            return Err(fail("a log entry proof has a member it may not have"));
1814        }
1815        if PROOF_REQUIRED.iter().any(|k| !p.contains_key(*k)) {
1816            return Err(fail("a log entry proof is missing a member"));
1817        }
1818        let text_of = |name: &str| p.get(name).and_then(Value::as_str);
1819        if text_of("type") != Some(PROOF_TYPE) {
1820            return Err(fail("a log entry proof is not a DataIntegrityProof"));
1821        }
1822        if text_of("cryptosuite") != Some(CRYPTOSUITE) {
1823            return Err(fail("a log entry proof must use eddsa-jcs-2022"));
1824        }
1825        if text_of("proofPurpose") != Some(PROOF_PURPOSE) {
1826            return Err(fail(
1827                "a log entry proof's proofPurpose must be assertionMethod",
1828            ));
1829        }
1830        if let Some(created) = p.get("created") {
1831            let valid = created
1832                .as_str()
1833                .is_some_and(|c| time::parse_protocol_time_ns(c).is_ok());
1834            if !valid {
1835                return Err(fail("a log entry proof's created is not a valid time"));
1836            }
1837        }
1838        let key = proof_key(p.get("verificationMethod"), number)?;
1839        if !authorized.contains(&key) {
1840            return Err(fail(
1841                "a log entry proof is not made by an authorized update key",
1842            ));
1843        }
1844        let signature = strict_signature(&p["proofValue"])
1845            .ok_or_else(|| fail("a log entry proof's proofValue is not an Ed25519 signature"))?;
1846        let raw = multikey::decode(&key)
1847            .ok()
1848            .filter(|d| d.algorithm == "Ed25519")
1849            .map(|d| d.raw_key)
1850            .ok_or_else(|| fail("a log entry proof's key is not an Ed25519 Multikey"))?;
1851        let document_hash = *document_hash
1852            .get_or_insert_with(|| Sha256::digest(jcs::canonicalize(&document)).into());
1853        // The proof configuration: the proof without proofValue, with the
1854        // document's @context when it has one (an entry never does).
1855        let mut config = p.clone();
1856        config.remove("proofValue");
1857        if let Some(context) = document.get("@context") {
1858            config.insert("@context".into(), context.clone());
1859        }
1860        let mut signing_input = [0u8; 64];
1861        signing_input[..32]
1862            .copy_from_slice(&Sha256::digest(jcs::canonicalize(&Value::Object(config))));
1863        signing_input[32..].copy_from_slice(&document_hash);
1864        let verified = keys::verify(&raw, &signing_input, &signature).ok();
1865        if verified != Some(true) {
1866            return Err(fail("a log entry proof does not verify"));
1867        }
1868    }
1869    Ok(())
1870}
1871
1872/// The state's `id` parses as a did:webvh DID with the log's SCID (spec
1873/// 3.6.2 step 6), and is the first entry's id: a DID that is not portable may
1874/// not move (spec 3.7.7), and moves of a portable DID are not supported.
1875fn check_state_id(
1876    state: &Value,
1877    scid: &str,
1878    first_id: Option<&str>,
1879    portable: bool,
1880    number: usize,
1881) -> Refusal<String> {
1882    let fail = |code, text| DidWebvhError::at(code, text, number);
1883    let Some(id) = state.get("id").and_then(Value::as_str) else {
1884        return Err(fail(INVALID_DID, "the state has no id"));
1885    };
1886    let parsed =
1887        parse(id).map_err(|_| fail(INVALID_DID, "the state id is not a bare did:webvh DID"))?;
1888    if parsed.scid != scid {
1889        return Err(fail(
1890            INVALID_DID,
1891            "the state id's SCID is not the DID's SCID",
1892        ));
1893    }
1894    if let Some(first) = first_id {
1895        if id != first {
1896            if !portable {
1897                return Err(fail(
1898                    INVALID_DID,
1899                    "the state id changed, but the DID is not portable",
1900                ));
1901            }
1902            return Err(fail(
1903                UNSUPPORTED,
1904                "did:webvh DIDs that move (portability) are not supported",
1905            ));
1906        }
1907    }
1908    Ok(id.to_string())
1909}
1910
1911struct Verified {
1912    entries: Vec<Value>,
1913    /// The parameters active after each entry.
1914    after: Vec<Active>,
1915    /// Each entry's versionTime, in nanoseconds.
1916    times: Vec<i128>,
1917}
1918
1919/// Verify every entry in order (step 2), then that the DID appears.
1920fn verify_entries(
1921    did: &DidWebvh,
1922    entries: Vec<Value>,
1923    now_ns: i128,
1924    limits: &Limits,
1925) -> Refusal<Verified> {
1926    let scid = did.scid.as_str();
1927    let limit_ns = now_ns + time::seconds_to_ns(MAX_FUTURE_SECONDS);
1928    let mut active = Active::initial();
1929    let mut after_each: Vec<Active> = Vec::with_capacity(entries.len());
1930    let mut times: Vec<i128> = Vec::with_capacity(entries.len());
1931    let mut previous_id = String::new();
1932    let mut previous_ns: Option<i128> = None;
1933    let mut first_id: Option<String> = None;
1934    let mut matches = 0usize;
1935
1936    for (index, entry) in entries.iter().enumerate() {
1937        let number = index + 1;
1938        let fail = |code, text| DidWebvhError::at(code, text, number);
1939        let pre_rotation = number > 1 && !active.next_key_hashes.is_empty();
1940        if number > 1 && active.deactivated {
1941            return Err(fail(
1942                INVALID_DID,
1943                "the DID log has an entry after the DID was deactivated",
1944            ));
1945        }
1946        if number > 1 && !pre_rotation && active.update_keys.is_empty() {
1947            return Err(fail(
1948                INVALID_DID,
1949                "the DID log has an entry after updateKeys was emptied",
1950            ));
1951        }
1952
1953        // versionId: "<number>-<entryHash>" (spec 3.6.2 step 3).
1954        let version_id = entry["versionId"].as_str().unwrap_or_default();
1955        let pieces: Vec<&str> = version_id.split('-').collect();
1956        if pieces.len() != 2 {
1957            return Err(fail(
1958                INVALID_DID,
1959                "a versionId must be its number, one dash and the entry hash",
1960            ));
1961        }
1962        let head = pieces[0].as_bytes();
1963        if head.is_empty()
1964            || !(b'1'..=b'9').contains(&head[0])
1965            || !head.iter().all(u8::is_ascii_digit)
1966        {
1967            return Err(fail(
1968                INVALID_DID,
1969                "a versionId number must be written without leading zeros",
1970            ));
1971        }
1972        if head.len() > 9 || pieces[0].parse::<usize>().ok() != Some(number) {
1973            return Err(fail(
1974                INVALID_DID,
1975                "the versionId numbers must run 1, 2, 3 and so on",
1976            ));
1977        }
1978        if !is_sha256_multihash(pieces[1]) {
1979            return Err(fail(
1980                INVALID_DID,
1981                "the entry hash is not a SHA-256 multihash",
1982            ));
1983        }
1984
1985        // versionTime (spec 3.6.2 step 4).
1986        let version_time = entry["versionTime"].as_str().unwrap_or_default();
1987        let moment_ns = time::parse_protocol_time_ns(version_time)
1988            .map_err(|_| fail(INVALID_DID, "a versionTime is not a valid time"))?;
1989        if !(version_time.ends_with('Z') || version_time.ends_with("+00:00")) {
1990            return Err(fail(
1991                INVALID_DID,
1992                "a versionTime must be in UTC (Z or +00:00)",
1993            ));
1994        }
1995        if previous_ns.is_some_and(|p| moment_ns <= p) {
1996            return Err(fail(
1997                INVALID_DID,
1998                "each versionTime must be later than the one before",
1999            ));
2000        }
2001        if moment_ns > limit_ns {
2002            return Err(fail(
2003                INVALID_DID,
2004                "a versionTime is more than five minutes in the future",
2005            ));
2006        }
2007
2008        // Parameters (spec 3.6.2 step 1, 3.7.1).
2009        let empty = Map::new();
2010        let given = entry["parameters"].as_object().unwrap_or(&empty);
2011        let after = check_parameters(given, &active, number, limits)?;
2012
2013        // Pre-rotation (spec 3.6.2 step 7, 3.7.6).
2014        if pre_rotation {
2015            let Some(keys) = given.get("updateKeys").and_then(string_list) else {
2016                return Err(fail(
2017                    INVALID_DID,
2018                    "under pre-rotation every entry must set updateKeys",
2019                ));
2020            };
2021            if keys
2022                .iter()
2023                .any(|k| !active.next_key_hashes.contains(&key_hash(k)))
2024            {
2025                return Err(fail(
2026                    INVALID_DID,
2027                    "an updateKeys key is not committed in the previous nextKeyHashes",
2028                ));
2029            }
2030            if !given.contains_key("nextKeyHashes") {
2031                return Err(fail(
2032                    INVALID_DID,
2033                    "under pre-rotation every entry must set nextKeyHashes",
2034                ));
2035            }
2036        }
2037
2038        // SCID (spec 3.6.2 step 5, 3.7.2).
2039        if number == 1 {
2040            if given.get("scid").and_then(Value::as_str) != Some(scid) {
2041                return Err(fail(INVALID_DID, "the log's scid is not the DID's SCID"));
2042            }
2043            check_scid(entry, scid)?;
2044        }
2045
2046        // Entry hash (spec 3.6.2 step 3, 3.7.3).
2047        let mut body = without_proof(entry);
2048        let predecessor = if number == 1 {
2049            scid
2050        } else {
2051            previous_id.as_str()
2052        };
2053        body.insert("versionId".into(), Value::String(predecessor.to_string()));
2054        if jcs_hash(&Value::Object(body)) != pieces[1] {
2055            return Err(fail(INVALID_DID, "the entry hash does not match the entry"));
2056        }
2057
2058        // Proofs by an authorized key (spec 3.6.2 step 2, 3.7.4, 3.7.5).
2059        let authorized: Vec<String> = if number == 1 || pre_rotation {
2060            after.update_keys.clone()
2061        } else {
2062            active.update_keys.clone()
2063        };
2064        check_proofs(entry, &authorized, number)?;
2065
2066        // The state's id (spec 3.6.2 step 6).
2067        let state_id = check_state_id(
2068            &entry["state"],
2069            scid,
2070            first_id.as_deref(),
2071            after.portable,
2072            number,
2073        )?;
2074        if first_id.is_none() {
2075            first_id = Some(state_id.clone());
2076        }
2077        if state_id == did.did {
2078            matches += 1;
2079        }
2080
2081        previous_id = version_id.to_string();
2082        previous_ns = Some(moment_ns);
2083        times.push(moment_ns);
2084        active = after.clone();
2085        after_each.push(after);
2086    }
2087
2088    if matches == 0 {
2089        return Err(invalid("no entry's state id is the DID being resolved"));
2090    }
2091    Ok(Verified {
2092        entries,
2093        after: after_each,
2094        times,
2095    })
2096}
2097
2098/// The version remembered from an earlier resolution is still in the log
2099/// (spec 4, "Truncation or withholding of log entries" and "split view").
2100fn check_seen(verified: &Verified, seen: &str) -> Refusal<()> {
2101    // VerifyOptions only holds a seen versionId that has a number.
2102    let number = version_number_of(seen).unwrap_or(usize::MAX);
2103    if number > verified.entries.len() {
2104        return Err(invalid("the DID log is older than a version seen before"));
2105    }
2106    if verified.entries[number - 1]["versionId"].as_str() != Some(seen) {
2107        return Err(invalid(
2108            "the DID log does not include a version seen before",
2109        ));
2110    }
2111    Ok(())
2112}
2113
2114/// The index of the entry a query names, else of the last entry.
2115fn select(verified: &Verified, query: &Query) -> Refusal<usize> {
2116    let entries = &verified.entries;
2117    match query {
2118        Query::Latest => Ok(entries.len() - 1),
2119        Query::VersionId(wanted) => entries
2120            .iter()
2121            .position(|e| e["versionId"].as_str() == Some(wanted.as_str()))
2122            .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "no entry has that versionId")),
2123        Query::VersionNumber(n) => {
2124            if *n >= 1 && (*n as u64) <= entries.len() as u64 {
2125                Ok(*n as usize - 1)
2126            } else {
2127                Err(DidWebvhError::new(
2128                    NOT_FOUND,
2129                    "no entry has that version number",
2130                ))
2131            }
2132        }
2133        Query::VersionTime(at) => {
2134            let wanted = time::parse_protocol_time_ns(at)
2135                .map_err(|_| invalid("the versionTime query is not a valid time"))?;
2136            verified
2137                .times
2138                .iter()
2139                .rposition(|t| *t <= wanted)
2140                .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "the DID did not exist at that time"))
2141        }
2142    }
2143}
2144
2145/// Verify a did:webvh log you already hold and resolve one version of it.
2146///
2147/// Pure and offline: nothing is fetched. Every entry is checked, in the
2148/// order the module documentation lists (spec 3.6.2, "Read (Resolve)"), and
2149/// any failure refuses the whole log, even for a query that names an earlier
2150/// entry.
2151///
2152/// `did` is the DID being resolved (a bare did:webvh DID), `log` the
2153/// `did.jsonl` bytes, and `now_ns` the resolver's time in nanoseconds since
2154/// the Unix epoch ([`crate::time::parse_protocol_time_ns`]); no versionTime
2155/// may be more than five minutes after it.
2156pub fn verify_log(
2157    did: &str,
2158    log: &[u8],
2159    now_ns: i128,
2160    options: &VerifyOptions,
2161) -> Refusal<Resolution> {
2162    let parsed = parse(did)?;
2163    let verified = verify_bytes(&parsed, log, now_ns, &options.limits)?;
2164    resolve_version(
2165        &parsed,
2166        &verified,
2167        options.seen_version_id.as_deref(),
2168        &options.query,
2169    )
2170}
2171
2172/// Steps 1 and 2 of the check order, and that some entry's state id is the
2173/// DID.
2174fn verify_bytes(parsed: &DidWebvh, log: &[u8], now_ns: i128, limits: &Limits) -> Refusal<Verified> {
2175    let entries = read_log(log, limits)?;
2176    verify_entries(parsed, entries, now_ns, limits)
2177}
2178
2179/// The rest of step 3 on a verified log: the version seen before (a
2180/// versionId, checked by the caller), the query, and that the selected
2181/// version is not the deactivated one. Then the resolution.
2182fn resolve_version(
2183    parsed: &DidWebvh,
2184    verified: &Verified,
2185    seen: Option<&str>,
2186    query: &Query,
2187) -> Refusal<Resolution> {
2188    if let Some(seen) = seen {
2189        check_seen(verified, seen)?;
2190    }
2191    let index = select(verified, query)?;
2192
2193    let last_index = verified.entries.len() - 1;
2194    let last = &verified.after[last_index];
2195    if index == last_index && last.deactivated {
2196        // The whole log verified, so its latest version is known: a caller
2197        // records it, and a log from before the deactivation is then refused.
2198        let mut error = DidWebvhError::new(DEACTIVATED, "the DID is deactivated");
2199        error.latest_version_id = verified.entries[last_index]["versionId"]
2200            .as_str()
2201            .map(str::to_string);
2202        return Err(error);
2203    }
2204    let selected = &verified.entries[index];
2205    let first = &verified.entries[0];
2206    let latest = &verified.entries[last_index];
2207    let metadata = json!({
2208        "versionId": selected["versionId"],
2209        "versionTime": selected["versionTime"],
2210        "created": first["versionTime"],
2211        "updated": latest["versionTime"],
2212        "scid": parsed.scid,
2213        "portable": last.portable,
2214        "deactivated": last.deactivated,
2215        "ttl": last.ttl.to_string(),
2216        "witness": {},
2217        "watchers": last.watchers,
2218    });
2219    Ok(Resolution {
2220        document: selected["state"].clone(),
2221        metadata,
2222        version_number: index + 1,
2223        latest_version_id: latest["versionId"].as_str().unwrap_or_default().to_string(),
2224    })
2225}
2226
2227// =============================================================================
2228// Logs for credential verification: the clock and the set of logs
2229// =============================================================================
2230
2231/// The clock a did:webvh log is checked against when it gives the keys of a
2232/// credential's issuer or of a delegation grant's issuer.
2233///
2234/// The reference resolves those logs against the time now, whatever time the
2235/// credential itself is checked at: the credential's `now` decides whether it
2236/// is within its validity window, and the log clock decides whether a log
2237/// entry is dated in the future. [`LogClock::At`] fixes the log clock
2238/// instead, for tests and replays.
2239#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2240pub enum LogClock {
2241    /// The system clock (the default, as in the reference).
2242    #[default]
2243    System,
2244    /// This time, in nanoseconds since the Unix epoch.
2245    At(i128),
2246}
2247
2248impl LogClock {
2249    /// The time this clock reads now, in nanoseconds since the Unix epoch.
2250    ///
2251    /// Errors for [`LogClock::System`] where there is no system clock
2252    /// (WebAssembly in a browser; the WASM build passes the JavaScript clock
2253    /// as [`LogClock::At`]).
2254    pub fn now_ns(self) -> Result<i128> {
2255        match self {
2256            Self::At(ns) => Ok(ns),
2257            Self::System => system_now_ns().ok_or_else(|| {
2258                CoreError::Json("there is no system clock here: give logNow".into())
2259            }),
2260        }
2261    }
2262}
2263
2264#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
2265fn system_now_ns() -> Option<i128> {
2266    use std::time::{SystemTime, UNIX_EPOCH};
2267    Some(match SystemTime::now().duration_since(UNIX_EPOCH) {
2268        Ok(after) => after.as_nanos() as i128,
2269        Err(before) => -(before.duration().as_nanos() as i128),
2270    })
2271}
2272
2273#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
2274fn system_now_ns() -> Option<i128> {
2275    None
2276}
2277
2278/// The did:webvh logs one credential verification uses, as the caller
2279/// fetched them: the issuer's, and those of delegation grant issuers.
2280///
2281/// The core keeps no state and never fetches. The caller fetches each log
2282/// from [`log_url`], gives the latest versionId it saw before for each DID
2283/// ([`LogSet::with_seen_version_id`]), and afterwards remembers the latest
2284/// versions the set reports ([`LogSet::outcomes`]), so a log later served
2285/// rolled back or forked is refused.
2286///
2287/// A log is verified the first time a verification needs it (credential
2288/// verification always uses the latest entry), against one clock read when
2289/// the set is made, and its latest state is then reused for the rest of that
2290/// verification, as the reference keeps one document per DID per
2291/// verification. Make one set per verification.
2292pub struct LogSet {
2293    now_ns: i128,
2294    limits: Limits,
2295    logs: BTreeMap<String, Vec<u8>>,
2296    seen: BTreeMap<String, String>,
2297    resolved: RefCell<BTreeMap<String, Refusal<Resolution>>>,
2298}
2299
2300impl fmt::Debug for LogSet {
2301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2302        f.debug_struct("LogSet")
2303            .field("now_ns", &self.now_ns)
2304            .field("limits", &self.limits)
2305            .field("dids", &self.logs.keys().collect::<Vec<_>>())
2306            .field("seen", &self.seen)
2307            .finish()
2308    }
2309}
2310
2311impl LogSet {
2312    /// An empty set whose logs are checked against `clock`, read now, with
2313    /// the default limits.
2314    ///
2315    /// Errors when the clock cannot be read (see [`LogClock::now_ns`]).
2316    pub fn new(clock: LogClock) -> Result<Self> {
2317        Ok(Self {
2318            now_ns: clock.now_ns()?,
2319            limits: Limits::default(),
2320            logs: BTreeMap::new(),
2321            seen: BTreeMap::new(),
2322            resolved: RefCell::new(BTreeMap::new()),
2323        })
2324    }
2325
2326    /// Check every log with these limits.
2327    pub fn with_limits(mut self, limits: Limits) -> Self {
2328        self.limits = limits;
2329        self
2330    }
2331
2332    /// The log (`did.jsonl`) of `did`, as fetched from [`log_url`].
2333    pub fn with_log(mut self, did: &str, log: Vec<u8>) -> Self {
2334        self.logs.insert(did.to_string(), log);
2335        self
2336    }
2337
2338    /// The latest versionId seen for `did` before. Its log must still
2339    /// contain it, so a log rolled back or forked since is refused.
2340    ///
2341    /// Errors when `seen` is not a did:webvh versionId.
2342    pub fn with_seen_version_id(mut self, did: &str, seen: &str) -> Result<Self> {
2343        if version_number_of(seen).is_none() {
2344            return Err(seen_version_id_error());
2345        }
2346        self.seen.insert(did.to_string(), seen.to_string());
2347        Ok(self)
2348    }
2349
2350    /// The time the logs are checked against, in nanoseconds since the Unix
2351    /// epoch.
2352    pub fn now_ns(&self) -> i128 {
2353        self.now_ns
2354    }
2355
2356    /// The limits every log is checked with.
2357    pub fn limits(&self) -> &Limits {
2358        &self.limits
2359    }
2360
2361    /// True when the set holds a log for `did`.
2362    pub fn contains(&self, did: &str) -> bool {
2363        self.logs.contains_key(did)
2364    }
2365
2366    /// The latest verified state of `did`'s log, or why the log was refused
2367    /// (a deactivated DID is `deactivated`). None when the set holds no log
2368    /// for `did`. The log is verified once; later calls reuse the answer.
2369    pub fn resolve(&self, did: &str) -> Option<Refusal<Resolution>> {
2370        if let Some(done) = self.resolved.borrow().get(did) {
2371            return Some(done.clone());
2372        }
2373        let log = self.logs.get(did)?;
2374        let mut options = VerifyOptions::new().with_limits(self.limits);
2375        // with_seen_version_id checked the form when the set was made.
2376        options.seen_version_id = self.seen.get(did).cloned();
2377        let answer = verify_log(did, log, self.now_ns, &options);
2378        self.resolved
2379            .borrow_mut()
2380            .insert(did.to_string(), answer.clone());
2381        Some(answer)
2382    }
2383
2384    /// Every log resolved so far, by DID: its latest versionId (remember it
2385    /// as the version seen for that DID), or why it was refused. A log the
2386    /// verification never needed is not listed.
2387    pub fn outcomes(&self) -> BTreeMap<String, Refusal<String>> {
2388        self.resolved
2389            .borrow()
2390            .iter()
2391            .map(|(did, answer)| {
2392                (
2393                    did.clone(),
2394                    answer
2395                        .as_ref()
2396                        .map(|r| r.latest_version_id.clone())
2397                        .map_err(Clone::clone),
2398                )
2399            })
2400            .collect()
2401    }
2402}
2403
2404// =============================================================================
2405// JSON in, JSON out (for the bindings)
2406// =============================================================================
2407
2408/// [`parse`] as JSON: `{"scid", "host", "port", "path", "url"}`, or
2409/// `{"error": {"code", "text"}}` for a refused DID.
2410pub fn parse_json(did: &str) -> Value {
2411    match parse(did) {
2412        Ok(parsed) => parsed.to_json(),
2413        Err(e) => json!({"error": {"code": e.code, "text": e.text}}),
2414    }
2415}
2416
2417pub(crate) fn base64_decode(text: &str, name: &str) -> Result<Vec<u8>> {
2418    use base64::{engine::general_purpose::STANDARD, Engine};
2419    STANDARD
2420        .decode(text)
2421        .map_err(|_| CoreError::Json(format!("{name} must be standard base64")))
2422}
2423
2424/// The log bytes of a request: `text_name` (the log as text) or `b64_name`
2425/// (its bytes in base64, for a log that is not UTF-8), exactly one.
2426fn log_bytes(request: &Map<String, Value>, text_name: &str, b64_name: &str) -> Result<Vec<u8>> {
2427    match (request.get(text_name), request.get(b64_name)) {
2428        (Some(Value::String(text)), None) => Ok(text.as_bytes().to_vec()),
2429        (None, Some(Value::String(b64))) => base64_decode(b64, b64_name),
2430        _ => Err(CoreError::Json(format!(
2431            "give the log as {text_name} (text) or {b64_name} (base64), exactly one"
2432        ))),
2433    }
2434}
2435
2436pub(crate) fn request_object<'a>(
2437    request: &'a Value,
2438    allowed: &[&str],
2439) -> Result<&'a Map<String, Value>> {
2440    let obj = request
2441        .as_object()
2442        .ok_or_else(|| CoreError::Json("the request must be a JSON object".into()))?;
2443    if let Some(name) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
2444        return Err(CoreError::Json(format!(
2445            "the request holds an unknown member {:?}",
2446            name.chars().take(40).collect::<String>()
2447        )));
2448    }
2449    Ok(obj)
2450}
2451
2452fn request_text<'a>(obj: &'a Map<String, Value>, name: &str) -> Result<&'a str> {
2453    obj.get(name)
2454        .and_then(Value::as_str)
2455        .ok_or_else(|| CoreError::Json(format!("{name} must be a string")))
2456}
2457
2458/// [`verify_log`] as JSON. The request is `{"did", "log" or "logB64", "now",
2459/// "options"}`: `log` is the log as text, `logB64` its bytes in base64 (for a
2460/// log that is not UTF-8), `now` a protocol time, and `options` (optional)
2461/// as [`VerifyOptions::from_json`] reads it.
2462///
2463/// Returns `{"document", "metadata", "versionNumber", "latestVersionId"}`,
2464/// or `{"error": {"code", "text", "entry"}}` when the DID or the log is
2465/// refused. A malformed request (a missing member, two queries, bad limits,
2466/// a seenVersionId that is not a versionId) is an `Err`.
2467///
2468/// The checks run in the reference's order, so a request that has both a
2469/// refusal and a mistake gives the same answer in every language: the
2470/// request, `now` and the limits; then the DID; then the query (at most one,
2471/// of the right type); then the log; and only then the form of the version
2472/// seen before, and the rest of step 3.
2473pub fn verify_log_json(request: &Value) -> Result<Value> {
2474    let obj = request_object(request, &["did", "log", "logB64", "now", "options"])?;
2475    let did = request_text(obj, "did")?;
2476    let log = log_bytes(obj, "log", "logB64")?;
2477    let now_ns = time::parse_protocol_time_ns(request_text(obj, "now")?)?;
2478    let empty = Map::new();
2479    let options = match obj.get("options") {
2480        None | Some(Value::Null) => &empty,
2481        Some(Value::Object(options)) => options,
2482        Some(_) => return Err(CoreError::Json("options must be a JSON object".into())),
2483    };
2484    let limits = match options.get("limits").filter(|v| !v.is_null()) {
2485        Some(v) => Limits::from_json(v)?,
2486        None => Limits::default(),
2487    };
2488    let refused = |e: DidWebvhError| json!({"error": e.to_json()});
2489    let parsed = match parse(did) {
2490        Ok(parsed) => parsed,
2491        Err(e) => return Ok(refused(e)),
2492    };
2493    let (query, seen) = read_query(options)?;
2494    let verified = match verify_bytes(&parsed, &log, now_ns, &limits) {
2495        Ok(verified) => verified,
2496        Err(e) => return Ok(refused(e)),
2497    };
2498    if seen
2499        .as_deref()
2500        .is_some_and(|s| version_number_of(s).is_none())
2501    {
2502        return Err(seen_version_id_error());
2503    }
2504    Ok(
2505        match resolve_version(&parsed, &verified, seen.as_deref(), &query) {
2506            Ok(resolution) => resolution.to_json(),
2507            Err(e) => refused(e),
2508        },
2509    )
2510}
2511
2512/// The request members every verify request shares for the delegation
2513/// chain and the did:webvh logs (see [`read_chain_request`]).
2514pub(crate) const CHAIN_REQUEST_MEMBERS: [&str; 12] = [
2515    "now",
2516    "clockSkewSeconds",
2517    "trustedRoots",
2518    "requirePostQuantum",
2519    "grantKeys",
2520    "grantMldsa44Keys",
2521    "grantSlhdsa128Keys",
2522    "grantLogs",
2523    "grantLogsB64",
2524    "grantSeenVersionIds",
2525    "limits",
2526    "logNow",
2527];
2528
2529/// The chain and log members of a verify request, read.
2530pub(crate) struct ChainRequest {
2531    pub(crate) now: String,
2532    pub(crate) skew: i64,
2533    pub(crate) roots: Option<Vec<String>>,
2534    pub(crate) require_pq: bool,
2535    pub(crate) grant_keys: Option<BTreeMap<String, Vec<u8>>>,
2536    pub(crate) grant_mldsa_keys: Option<BTreeMap<String, Vec<u8>>>,
2537    pub(crate) grant_slhdsa_keys: Option<BTreeMap<String, Vec<u8>>>,
2538    /// The grant issuers' logs and versions seen, with the limits and the
2539    /// clock. The did:webvh credential request adds the issuer's log.
2540    pub(crate) logs: LogSet,
2541}
2542
2543fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
2544    obj.get(name).filter(|v| !v.is_null())
2545}
2546
2547/// A JSON object of DID to text, or None when absent.
2548fn text_map<'a>(
2549    obj: &'a Map<String, Value>,
2550    name: &str,
2551    what: &str,
2552) -> Result<Option<Vec<(&'a String, &'a str)>>> {
2553    let bad = || CoreError::Json(format!("{name} must be a JSON object of DID to {what}"));
2554    match present(obj, name) {
2555        None => Ok(None),
2556        Some(Value::Object(map)) => map
2557            .iter()
2558            .map(|(did, v)| v.as_str().map(|t| (did, t)).ok_or_else(bad))
2559            .collect::<Result<Vec<_>>>()
2560            .map(Some),
2561        Some(_) => Err(bad()),
2562    }
2563}
2564
2565/// A JSON object of DID to base64 key, decoded.
2566fn key_map(obj: &Map<String, Value>, name: &str) -> Result<Option<BTreeMap<String, Vec<u8>>>> {
2567    match text_map(obj, name, "base64 key")? {
2568        None => Ok(None),
2569        Some(items) => items
2570            .into_iter()
2571            .map(|(did, key)| Ok((did.clone(), base64_decode(key, &format!("a {name} key"))?)))
2572            .collect::<Result<_>>()
2573            .map(Some),
2574    }
2575}
2576
2577/// Read the members of a verify request that every entry shares:
2578///
2579/// - `now` (a protocol time, required) and `clockSkewSeconds` (0 to 120,
2580///   default 0): the credential's own clock;
2581/// - `trustedRoots` (optional): the DIDs a delegation chain must start from;
2582///   without it a credential carrying a chain is refused;
2583/// - `requirePostQuantum` (default false);
2584/// - `grantKeys` (optional): Ed25519 keys (base64) of grant issuers that are
2585///   not did:key, by DID. They resolve grant signatures only and never make
2586///   a DID a trusted root;
2587/// - `grantMldsa44Keys` (optional): ML-DSA-44 keys (base64) of grant
2588///   issuers, by DID;
2589/// - `grantLogs` / `grantLogsB64` (optional): the `did.jsonl` of did:webvh
2590///   grant issuers, by DID, as text or base64 (a DID in at most one);
2591/// - `grantSeenVersionIds` (optional): the latest versionId seen before for
2592///   each of those DIDs;
2593/// - `limits` (optional): as [`Limits::from_json`], for every log;
2594/// - `logNow` (optional): a protocol time to check the logs against, for
2595///   tests and replays. Without it the logs are checked against `clock`.
2596pub(crate) fn read_chain_request(
2597    obj: &Map<String, Value>,
2598    clock: LogClock,
2599) -> Result<ChainRequest> {
2600    let now = request_text(obj, "now")?.to_string();
2601    time::parse_protocol_time_ns(&now)?;
2602    let skew = match present(obj, "clockSkewSeconds") {
2603        None => 0,
2604        Some(v) => time::clock_skew_from_json(v)?,
2605    };
2606    let roots = match present(obj, "trustedRoots") {
2607        None => None,
2608        Some(v) => Some(
2609            string_list(v)
2610                .ok_or_else(|| CoreError::Json("trustedRoots must be a list of strings".into()))?
2611                .into_iter()
2612                .map(str::to_string)
2613                .collect(),
2614        ),
2615    };
2616    let require_pq = match present(obj, "requirePostQuantum") {
2617        None => false,
2618        Some(Value::Bool(b)) => *b,
2619        Some(_) => {
2620            return Err(CoreError::Json(
2621                "requirePostQuantum must be true or false".into(),
2622            ))
2623        }
2624    };
2625    let grant_keys = key_map(obj, "grantKeys")?;
2626    let grant_mldsa_keys = key_map(obj, "grantMldsa44Keys")?;
2627    let grant_slhdsa_keys = key_map(obj, "grantSlhdsa128Keys")?;
2628    let clock = match present(obj, "logNow") {
2629        None => clock,
2630        Some(v) => LogClock::At(time::parse_protocol_time_ns(
2631            v.as_str()
2632                .ok_or_else(|| CoreError::Json("logNow must be a protocol time".into()))?,
2633        )?),
2634    };
2635    let mut logs = LogSet::new(clock)?;
2636    if let Some(limits) = present(obj, "limits") {
2637        logs = logs.with_limits(Limits::from_json(limits)?);
2638    }
2639    let texts = text_map(obj, "grantLogs", "log text")?.unwrap_or_default();
2640    let b64s = text_map(obj, "grantLogsB64", "base64 log")?.unwrap_or_default();
2641    for (did, log) in texts
2642        .into_iter()
2643        .map(|(did, text)| Ok((did, text.as_bytes().to_vec())))
2644        .chain(
2645            b64s.into_iter()
2646                .map(|(did, b64)| Ok((did, base64_decode(b64, "a grantLogsB64 log")?))),
2647        )
2648        .collect::<Result<Vec<_>>>()?
2649    {
2650        if !is_did_webvh(did) {
2651            return Err(CoreError::Json(
2652                "grantLogs holds a DID that is not a did:webvh DID".into(),
2653            ));
2654        }
2655        if logs.contains(did) {
2656            return Err(CoreError::Json(
2657                "give each grant issuer's log once, in grantLogs or grantLogsB64".into(),
2658            ));
2659        }
2660        logs = logs.with_log(did, log);
2661    }
2662    for (did, seen) in text_map(obj, "grantSeenVersionIds", "versionId")?.unwrap_or_default() {
2663        logs = logs.with_seen_version_id(did, seen)?;
2664    }
2665    Ok(ChainRequest {
2666        now,
2667        skew,
2668        roots,
2669        require_pq,
2670        grant_keys,
2671        grant_mldsa_keys,
2672        grant_slhdsa_keys,
2673        logs,
2674    })
2675}
2676
2677/// The grant logs a verification resolved, as two JSON objects:
2678/// `grantVersionIds` (DID to latest versionId) and `grantLogErrors` (DID to
2679/// `{"code", "text", "entry"}`).
2680pub(crate) fn grant_log_json(outcomes: &BTreeMap<String, Refusal<String>>) -> (Value, Value) {
2681    let mut versions = Map::new();
2682    let mut errors = Map::new();
2683    for (did, outcome) in outcomes {
2684        match outcome {
2685            Ok(version) => {
2686                versions.insert(did.clone(), Value::String(version.clone()));
2687            }
2688            Err(e) => {
2689                errors.insert(did.clone(), e.to_json());
2690            }
2691        }
2692    }
2693    (Value::Object(versions), Value::Object(errors))
2694}
2695
2696/// [`crate::credentials::verify_with_did_webvh_log`] as JSON, with the logs
2697/// checked against the system clock (see [`verify_credential_json_with_clock`]).
2698pub fn verify_credential_json(request: &Value) -> Result<Value> {
2699    verify_credential_json_with_clock(request, LogClock::System)
2700}
2701
2702/// [`crate::credentials::verify_with_did_webvh_log`] as JSON. The request is
2703/// `{"credential", "issuerLog" or "issuerLogB64", "seenVersionId"}` plus the
2704/// members [`read_chain_request`] reads (`now`, `clockSkewSeconds`,
2705/// `trustedRoots`, `requirePostQuantum`, `grantKeys`, `grantMldsa44Keys`,
2706/// `grantLogs`, `grantLogsB64`, `grantSeenVersionIds`, `limits`, `logNow`):
2707///
2708/// - `credential`: the credential (a JSON object) whose issuer is a
2709///   did:webvh DID;
2710/// - `issuerLog` / `issuerLogB64`: the issuer's `did.jsonl`, fetched by the
2711///   caller from [`log_url`], as text or base64, exactly one;
2712/// - `seenVersionId` (optional): the latest versionId seen before for the
2713///   issuer.
2714///
2715/// Every log is checked against `logNow` when the request gives one, else
2716/// against `clock` (the system clock for [`verify_credential_json`]), never
2717/// against the credential's `now`.
2718///
2719/// Returns `{"proofValid", "timeValid", "chainValid", "valid",
2720/// "chainReason", "issuerVersionId", "issuerLogError", "grantVersionIds",
2721/// "grantLogErrors"}`: `issuerVersionId` is the issuer log's latest
2722/// versionId (remember it as the version seen) and `issuerLogError` is null,
2723/// or `{"code", "text", "entry"}` when the log was refused (the proof is then
2724/// not valid); `grantVersionIds` and `grantLogErrors` say the same, by DID,
2725/// for the grant issuers' logs the chain needed.
2726pub fn verify_credential_json_with_clock(request: &Value, clock: LogClock) -> Result<Value> {
2727    let mut allowed = vec!["credential", "issuerLog", "issuerLogB64", "seenVersionId"];
2728    allowed.extend(CHAIN_REQUEST_MEMBERS);
2729    let obj = request_object(request, &allowed)?;
2730    let credential = obj
2731        .get("credential")
2732        .filter(|c| c.is_object())
2733        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
2734    let log = log_bytes(obj, "issuerLog", "issuerLogB64")?;
2735    let request = read_chain_request(obj, clock)?;
2736    let issuer = crate::credentials::issuer_did(credential)
2737        .filter(|i| is_did_webvh(i))
2738        .ok_or_else(|| {
2739            CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
2740        })?;
2741    if request.logs.contains(issuer) {
2742        return Err(CoreError::Json(
2743            "give the issuer's log once, as issuerLog or issuerLogB64".into(),
2744        ));
2745    }
2746    let mut logs = request.logs.with_log(issuer, log);
2747    if let Some(seen) = present(obj, "seenVersionId") {
2748        let seen = seen
2749            .as_str()
2750            .ok_or_else(|| CoreError::Json("seenVersionId must be a string".into()))?;
2751        logs = logs.with_seen_version_id(issuer, seen)?;
2752    }
2753    let chain = crate::delegation::ChainOptions {
2754        trusted_roots: request.roots.as_deref(),
2755        grant_keys: request.grant_keys.as_ref(),
2756        mldsa_keys: request.grant_mldsa_keys.as_ref(),
2757        slhdsa_keys: request.grant_slhdsa_keys.as_ref(),
2758        require_pq: request.require_pq,
2759        ..Default::default()
2760    };
2761    let outcome = crate::credentials::verify_with_did_webvh_log(
2762        credential,
2763        &logs,
2764        &request.now,
2765        request.skew,
2766        &chain,
2767    )?;
2768    let r = outcome.result;
2769    let (grant_versions, grant_errors) = grant_log_json(&outcome.grant_logs);
2770    Ok(json!({
2771        "proofValid": r.proof_valid,
2772        "timeValid": r.time_valid,
2773        "chainValid": r.chain_valid,
2774        "valid": r.is_valid(),
2775        "chainReason": outcome.chain_reason,
2776        "issuerVersionId": outcome.log.as_ref().ok(),
2777        "issuerLogError": outcome.log.as_ref().err().map(DidWebvhError::to_json),
2778        "grantVersionIds": grant_versions,
2779        "grantLogErrors": grant_errors,
2780    }))
2781}
2782
2783#[cfg(test)]
2784mod tests {
2785    use super::*;
2786
2787    #[test]
2788    fn depth_scan_counts_brackets_outside_strings() {
2789        let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
2790        assert!(!json_too_deep(nested(64).as_bytes(), 64));
2791        assert!(json_too_deep(nested(65).as_bytes(), 64));
2792        // Brackets inside strings, escaped quotes included, do not count.
2793        let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
2794        assert!(!json_too_deep(quoted.as_bytes(), 64));
2795        // A string with no closing quote runs to the end.
2796        assert!(!json_too_deep(b"{\"a\":\"[[[[", 2));
2797    }
2798
2799    #[test]
2800    fn reader_reports_problems_where_python_does() {
2801        let read = |s: &str| read_json_line(s.as_bytes());
2802        assert_eq!(read(r#"{"a":1,"a":2}"#).unwrap_err(), JsonProblem::Repeated);
2803        // A repeated name in an object still open does not count before a
2804        // number out of range later in it.
2805        assert_eq!(
2806            read(r#"{"a":1,"a":2,"b":99999999999999999}"#).unwrap_err(),
2807            JsonProblem::OutOfRange
2808        );
2809        assert_eq!(
2810            read(r#"{"x":{"a":1,"a":2},"b":1e999}"#).unwrap_err(),
2811            JsonProblem::Repeated
2812        );
2813        assert_eq!(
2814            read(r#"{"a":1,"a":2,"b":tru}"#).unwrap_err(),
2815            JsonProblem::Invalid
2816        );
2817        // The integer part is read (and range-checked) before a bad exponent.
2818        assert_eq!(
2819            read(r#"{"a":99999999999999999e}"#).unwrap_err(),
2820            JsonProblem::OutOfRange
2821        );
2822        assert_eq!(read(r#"{"a":1e}"#).unwrap_err(), JsonProblem::Invalid);
2823        assert_eq!(read(r#"{"a":NaN}"#).unwrap_err(), JsonProblem::Invalid);
2824        assert_eq!(
2825            read(r#"{"a":-Infinity}"#).unwrap_err(),
2826            JsonProblem::Invalid
2827        );
2828        assert_eq!(read(r#"{"a":01}"#).unwrap_err(), JsonProblem::Invalid);
2829        assert_eq!(read(r#"{"a":[1,]}"#).unwrap_err(), JsonProblem::Invalid);
2830        assert_eq!(read(r#"{"a":1,}"#).unwrap_err(), JsonProblem::Invalid);
2831        assert_eq!(read("{\"a\":\"\t\"}").unwrap_err(), JsonProblem::Invalid);
2832        assert_eq!(read(r#"{"a":"\x"}"#).unwrap_err(), JsonProblem::Invalid);
2833        assert_eq!(read(r#"{}{}"#).unwrap_err(), JsonProblem::Invalid);
2834        assert_eq!(
2835            read(r#"{"a":9007199254740991}"#).unwrap().0["a"],
2836            9007199254740991i64
2837        );
2838        assert_eq!(
2839            read(r#"{"a":-9007199254740992}"#).unwrap_err(),
2840            JsonProblem::OutOfRange
2841        );
2842        assert_eq!(
2843            read(r#"{"a":9007199254740992.0}"#).unwrap_err(),
2844            JsonProblem::OutOfRange
2845        );
2846        // Lone surrogates are remembered; two different ones are two names.
2847        assert!(read(r#"{"a":"\ud800"}"#).unwrap().1);
2848        assert!(read(r#"{"\ud800":1,"\udc00":2}"#).unwrap().1);
2849        assert_eq!(
2850            read(r#"{"\ud800":1,"\ud800":2}"#).unwrap_err(),
2851            JsonProblem::Repeated
2852        );
2853        // A pair is one character, and the same name as the raw character.
2854        let (v, lone) = read(r#"{"a":"😀"}"#).unwrap();
2855        assert!(!lone);
2856        assert_eq!(v["a"], "\u{1F600}");
2857        assert_eq!(
2858            read("{\"\u{1F600}\":1,\"\\ud83d\\ude00\":2}").unwrap_err(),
2859            JsonProblem::Repeated
2860        );
2861        assert_eq!(
2862            read(r#"{"a":"a","a":1}"#).unwrap_err(),
2863            JsonProblem::Repeated
2864        );
2865    }
2866
2867    #[test]
2868    fn options_from_json() {
2869        assert!(
2870            VerifyOptions::from_json(&json!({"versionId": "1-x", "versionNumber": 1})).is_err()
2871        );
2872        assert!(VerifyOptions::from_json(&json!({"versionNumber": 1.0})).is_err());
2873        assert!(VerifyOptions::from_json(&json!({"versionNumber": true})).is_err());
2874        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "01-x"})).is_err());
2875        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "1"})).is_err());
2876        assert!(VerifyOptions::from_json(&json!({"other": 1})).is_err());
2877        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 0}})).is_err());
2878        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 5242881}})).is_err());
2879        assert!(VerifyOptions::from_json(&json!({"limits": {"maxProofs": true}})).is_err());
2880        assert!(VerifyOptions::from_json(&json!({"limits": {"maxx": 1}})).is_err());
2881        let o = VerifyOptions::from_json(
2882            &json!({"versionId": null, "versionTime": "x", "limits": {"maxEntries": 2}}),
2883        )
2884        .unwrap();
2885        assert_eq!(o.query(), &Query::VersionTime("x".into()));
2886        assert_eq!(o.limits().max_entries(), 2);
2887        assert_eq!(o.limits().max_bytes(), 1024 * 1024);
2888        assert_eq!(
2889            VerifyOptions::from_json(&json!({"versionNumber": u64::MAX}))
2890                .unwrap()
2891                .query(),
2892            &Query::VersionNumber(i64::MAX)
2893        );
2894    }
2895
2896    /// The `create` log of the shared vector, with its proofValue's R
2897    /// replaced by `r`.
2898    fn create_log_with_r(r: [u8; 32]) -> (String, String) {
2899        let path = concat!(
2900            env!("CARGO_MANIFEST_DIR"),
2901            "/../../test-vectors/did-webvh/vector.json"
2902        );
2903        let v: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
2904        let case = v["logs"]
2905            .as_array()
2906            .unwrap()
2907            .iter()
2908            .find(|c| c["name"] == "create")
2909            .unwrap();
2910        let log = case["log"].as_str().unwrap();
2911        let entry: Value = serde_json::from_str(log.trim_end()).unwrap();
2912        let value = entry["proof"][0]["proofValue"].as_str().unwrap();
2913        let mut signature = bs58::decode(&value[1..]).into_vec().unwrap();
2914        signature[..32].copy_from_slice(&r);
2915        let changed = format!("z{}", bs58::encode(signature).into_string());
2916        (
2917            case["did"].as_str().unwrap().to_string(),
2918            log.replace(value, &changed),
2919        )
2920    }
2921
2922    fn refusal(did: &str, log: &str) -> DidWebvhError {
2923        let now = time::parse_protocol_time_ns("2026-11-30T00:00:00Z").unwrap();
2924        verify_log(did, log.as_bytes(), now, &VerifyOptions::new()).unwrap_err()
2925    }
2926
2927    #[test]
2928    fn an_r_off_the_curve_fails_at_verification() {
2929        // A y below p (a canonical encoding) that names no point on the curve.
2930        let off_curve = (2u8..=255)
2931            .map(|y| {
2932                let mut r = [0u8; 32];
2933                r[0] = y;
2934                r
2935            })
2936            .find(|r| ed25519_dalek::VerifyingKey::from_bytes(r).is_err())
2937            .expect("a y with no point");
2938        assert!(keys::is_canonical_point_encoding(&off_curve));
2939        // The form check lets it through, as the reference's does ...
2940        let mut signature = vec![0u8; 64];
2941        signature[..32].copy_from_slice(&off_curve);
2942        let value = Value::String(format!("z{}", bs58::encode(&signature).into_string()));
2943        assert!(strict_signature(&value).is_some());
2944        // ... and the proof then does not verify.
2945        let (did, log) = create_log_with_r(off_curve);
2946        let e = refusal(&did, &log);
2947        assert_eq!(
2948            (e.code, e.text, e.entry),
2949            (INVALID_DID, "a log entry proof does not verify", Some(1))
2950        );
2951    }
2952
2953    #[test]
2954    fn a_small_order_or_non_canonical_r_is_not_a_signature() {
2955        for hex in SMALL_ORDER_ENCODINGS {
2956            let mut r = [0u8; 32];
2957            for (i, b) in r.iter_mut().enumerate() {
2958                *b = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap();
2959            }
2960            let (did, log) = create_log_with_r(r);
2961            let e = refusal(&did, &log);
2962            assert_eq!(
2963                (e.text, e.entry),
2964                (
2965                    "a log entry proof's proofValue is not an Ed25519 signature",
2966                    Some(1)
2967                ),
2968                "{hex}"
2969            );
2970        }
2971        // y >= p that is not of small order (y = p + 3).
2972        let mut r = [0xffu8; 32];
2973        r[0] = 0xf0;
2974        r[31] = 0x7f;
2975        let (did, log) = create_log_with_r(r);
2976        assert_eq!(
2977            refusal(&did, &log).text,
2978            "a log entry proof's proofValue is not an Ed25519 signature"
2979        );
2980    }
2981
2982    #[test]
2983    fn prefix_keeps_its_colon() {
2984        assert!(is_did_webvh("did:webvh:x"));
2985        assert!(!is_did_webvh("did:web:x"));
2986        assert!(!is_did_webvh("did:webvhx:x"));
2987        assert_eq!(
2988            parse("did:web:example.com").unwrap_err().text,
2989            "not a did:webvh DID"
2990        );
2991    }
2992}