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            .map(|d| d.raw_key)
1848            .map_err(|_| fail("a log entry proof's key is not an Ed25519 Multikey"))?;
1849        let document_hash = *document_hash
1850            .get_or_insert_with(|| Sha256::digest(jcs::canonicalize(&document)).into());
1851        // The proof configuration: the proof without proofValue, with the
1852        // document's @context when it has one (an entry never does).
1853        let mut config = p.clone();
1854        config.remove("proofValue");
1855        if let Some(context) = document.get("@context") {
1856            config.insert("@context".into(), context.clone());
1857        }
1858        let mut signing_input = [0u8; 64];
1859        signing_input[..32]
1860            .copy_from_slice(&Sha256::digest(jcs::canonicalize(&Value::Object(config))));
1861        signing_input[32..].copy_from_slice(&document_hash);
1862        let verified = keys::verify(&raw, &signing_input, &signature).ok();
1863        if verified != Some(true) {
1864            return Err(fail("a log entry proof does not verify"));
1865        }
1866    }
1867    Ok(())
1868}
1869
1870/// The state's `id` parses as a did:webvh DID with the log's SCID (spec
1871/// 3.6.2 step 6), and is the first entry's id: a DID that is not portable may
1872/// not move (spec 3.7.7), and moves of a portable DID are not supported.
1873fn check_state_id(
1874    state: &Value,
1875    scid: &str,
1876    first_id: Option<&str>,
1877    portable: bool,
1878    number: usize,
1879) -> Refusal<String> {
1880    let fail = |code, text| DidWebvhError::at(code, text, number);
1881    let Some(id) = state.get("id").and_then(Value::as_str) else {
1882        return Err(fail(INVALID_DID, "the state has no id"));
1883    };
1884    let parsed =
1885        parse(id).map_err(|_| fail(INVALID_DID, "the state id is not a bare did:webvh DID"))?;
1886    if parsed.scid != scid {
1887        return Err(fail(
1888            INVALID_DID,
1889            "the state id's SCID is not the DID's SCID",
1890        ));
1891    }
1892    if let Some(first) = first_id {
1893        if id != first {
1894            if !portable {
1895                return Err(fail(
1896                    INVALID_DID,
1897                    "the state id changed, but the DID is not portable",
1898                ));
1899            }
1900            return Err(fail(
1901                UNSUPPORTED,
1902                "did:webvh DIDs that move (portability) are not supported",
1903            ));
1904        }
1905    }
1906    Ok(id.to_string())
1907}
1908
1909struct Verified {
1910    entries: Vec<Value>,
1911    /// The parameters active after each entry.
1912    after: Vec<Active>,
1913    /// Each entry's versionTime, in nanoseconds.
1914    times: Vec<i128>,
1915}
1916
1917/// Verify every entry in order (step 2), then that the DID appears.
1918fn verify_entries(
1919    did: &DidWebvh,
1920    entries: Vec<Value>,
1921    now_ns: i128,
1922    limits: &Limits,
1923) -> Refusal<Verified> {
1924    let scid = did.scid.as_str();
1925    let limit_ns = now_ns + time::seconds_to_ns(MAX_FUTURE_SECONDS);
1926    let mut active = Active::initial();
1927    let mut after_each: Vec<Active> = Vec::with_capacity(entries.len());
1928    let mut times: Vec<i128> = Vec::with_capacity(entries.len());
1929    let mut previous_id = String::new();
1930    let mut previous_ns: Option<i128> = None;
1931    let mut first_id: Option<String> = None;
1932    let mut matches = 0usize;
1933
1934    for (index, entry) in entries.iter().enumerate() {
1935        let number = index + 1;
1936        let fail = |code, text| DidWebvhError::at(code, text, number);
1937        let pre_rotation = number > 1 && !active.next_key_hashes.is_empty();
1938        if number > 1 && active.deactivated {
1939            return Err(fail(
1940                INVALID_DID,
1941                "the DID log has an entry after the DID was deactivated",
1942            ));
1943        }
1944        if number > 1 && !pre_rotation && active.update_keys.is_empty() {
1945            return Err(fail(
1946                INVALID_DID,
1947                "the DID log has an entry after updateKeys was emptied",
1948            ));
1949        }
1950
1951        // versionId: "<number>-<entryHash>" (spec 3.6.2 step 3).
1952        let version_id = entry["versionId"].as_str().unwrap_or_default();
1953        let pieces: Vec<&str> = version_id.split('-').collect();
1954        if pieces.len() != 2 {
1955            return Err(fail(
1956                INVALID_DID,
1957                "a versionId must be its number, one dash and the entry hash",
1958            ));
1959        }
1960        let head = pieces[0].as_bytes();
1961        if head.is_empty()
1962            || !(b'1'..=b'9').contains(&head[0])
1963            || !head.iter().all(u8::is_ascii_digit)
1964        {
1965            return Err(fail(
1966                INVALID_DID,
1967                "a versionId number must be written without leading zeros",
1968            ));
1969        }
1970        if head.len() > 9 || pieces[0].parse::<usize>().ok() != Some(number) {
1971            return Err(fail(
1972                INVALID_DID,
1973                "the versionId numbers must run 1, 2, 3 and so on",
1974            ));
1975        }
1976        if !is_sha256_multihash(pieces[1]) {
1977            return Err(fail(
1978                INVALID_DID,
1979                "the entry hash is not a SHA-256 multihash",
1980            ));
1981        }
1982
1983        // versionTime (spec 3.6.2 step 4).
1984        let version_time = entry["versionTime"].as_str().unwrap_or_default();
1985        let moment_ns = time::parse_protocol_time_ns(version_time)
1986            .map_err(|_| fail(INVALID_DID, "a versionTime is not a valid time"))?;
1987        if !(version_time.ends_with('Z') || version_time.ends_with("+00:00")) {
1988            return Err(fail(
1989                INVALID_DID,
1990                "a versionTime must be in UTC (Z or +00:00)",
1991            ));
1992        }
1993        if previous_ns.is_some_and(|p| moment_ns <= p) {
1994            return Err(fail(
1995                INVALID_DID,
1996                "each versionTime must be later than the one before",
1997            ));
1998        }
1999        if moment_ns > limit_ns {
2000            return Err(fail(
2001                INVALID_DID,
2002                "a versionTime is more than five minutes in the future",
2003            ));
2004        }
2005
2006        // Parameters (spec 3.6.2 step 1, 3.7.1).
2007        let empty = Map::new();
2008        let given = entry["parameters"].as_object().unwrap_or(&empty);
2009        let after = check_parameters(given, &active, number, limits)?;
2010
2011        // Pre-rotation (spec 3.6.2 step 7, 3.7.6).
2012        if pre_rotation {
2013            let Some(keys) = given.get("updateKeys").and_then(string_list) else {
2014                return Err(fail(
2015                    INVALID_DID,
2016                    "under pre-rotation every entry must set updateKeys",
2017                ));
2018            };
2019            if keys
2020                .iter()
2021                .any(|k| !active.next_key_hashes.contains(&key_hash(k)))
2022            {
2023                return Err(fail(
2024                    INVALID_DID,
2025                    "an updateKeys key is not committed in the previous nextKeyHashes",
2026                ));
2027            }
2028            if !given.contains_key("nextKeyHashes") {
2029                return Err(fail(
2030                    INVALID_DID,
2031                    "under pre-rotation every entry must set nextKeyHashes",
2032                ));
2033            }
2034        }
2035
2036        // SCID (spec 3.6.2 step 5, 3.7.2).
2037        if number == 1 {
2038            if given.get("scid").and_then(Value::as_str) != Some(scid) {
2039                return Err(fail(INVALID_DID, "the log's scid is not the DID's SCID"));
2040            }
2041            check_scid(entry, scid)?;
2042        }
2043
2044        // Entry hash (spec 3.6.2 step 3, 3.7.3).
2045        let mut body = without_proof(entry);
2046        let predecessor = if number == 1 {
2047            scid
2048        } else {
2049            previous_id.as_str()
2050        };
2051        body.insert("versionId".into(), Value::String(predecessor.to_string()));
2052        if jcs_hash(&Value::Object(body)) != pieces[1] {
2053            return Err(fail(INVALID_DID, "the entry hash does not match the entry"));
2054        }
2055
2056        // Proofs by an authorized key (spec 3.6.2 step 2, 3.7.4, 3.7.5).
2057        let authorized: Vec<String> = if number == 1 || pre_rotation {
2058            after.update_keys.clone()
2059        } else {
2060            active.update_keys.clone()
2061        };
2062        check_proofs(entry, &authorized, number)?;
2063
2064        // The state's id (spec 3.6.2 step 6).
2065        let state_id = check_state_id(
2066            &entry["state"],
2067            scid,
2068            first_id.as_deref(),
2069            after.portable,
2070            number,
2071        )?;
2072        if first_id.is_none() {
2073            first_id = Some(state_id.clone());
2074        }
2075        if state_id == did.did {
2076            matches += 1;
2077        }
2078
2079        previous_id = version_id.to_string();
2080        previous_ns = Some(moment_ns);
2081        times.push(moment_ns);
2082        active = after.clone();
2083        after_each.push(after);
2084    }
2085
2086    if matches == 0 {
2087        return Err(invalid("no entry's state id is the DID being resolved"));
2088    }
2089    Ok(Verified {
2090        entries,
2091        after: after_each,
2092        times,
2093    })
2094}
2095
2096/// The version remembered from an earlier resolution is still in the log
2097/// (spec 4, "Truncation or withholding of log entries" and "split view").
2098fn check_seen(verified: &Verified, seen: &str) -> Refusal<()> {
2099    // VerifyOptions only holds a seen versionId that has a number.
2100    let number = version_number_of(seen).unwrap_or(usize::MAX);
2101    if number > verified.entries.len() {
2102        return Err(invalid("the DID log is older than a version seen before"));
2103    }
2104    if verified.entries[number - 1]["versionId"].as_str() != Some(seen) {
2105        return Err(invalid(
2106            "the DID log does not include a version seen before",
2107        ));
2108    }
2109    Ok(())
2110}
2111
2112/// The index of the entry a query names, else of the last entry.
2113fn select(verified: &Verified, query: &Query) -> Refusal<usize> {
2114    let entries = &verified.entries;
2115    match query {
2116        Query::Latest => Ok(entries.len() - 1),
2117        Query::VersionId(wanted) => entries
2118            .iter()
2119            .position(|e| e["versionId"].as_str() == Some(wanted.as_str()))
2120            .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "no entry has that versionId")),
2121        Query::VersionNumber(n) => {
2122            if *n >= 1 && (*n as u64) <= entries.len() as u64 {
2123                Ok(*n as usize - 1)
2124            } else {
2125                Err(DidWebvhError::new(
2126                    NOT_FOUND,
2127                    "no entry has that version number",
2128                ))
2129            }
2130        }
2131        Query::VersionTime(at) => {
2132            let wanted = time::parse_protocol_time_ns(at)
2133                .map_err(|_| invalid("the versionTime query is not a valid time"))?;
2134            verified
2135                .times
2136                .iter()
2137                .rposition(|t| *t <= wanted)
2138                .ok_or_else(|| DidWebvhError::new(NOT_FOUND, "the DID did not exist at that time"))
2139        }
2140    }
2141}
2142
2143/// Verify a did:webvh log you already hold and resolve one version of it.
2144///
2145/// Pure and offline: nothing is fetched. Every entry is checked, in the
2146/// order the module documentation lists (spec 3.6.2, "Read (Resolve)"), and
2147/// any failure refuses the whole log, even for a query that names an earlier
2148/// entry.
2149///
2150/// `did` is the DID being resolved (a bare did:webvh DID), `log` the
2151/// `did.jsonl` bytes, and `now_ns` the resolver's time in nanoseconds since
2152/// the Unix epoch ([`crate::time::parse_protocol_time_ns`]); no versionTime
2153/// may be more than five minutes after it.
2154pub fn verify_log(
2155    did: &str,
2156    log: &[u8],
2157    now_ns: i128,
2158    options: &VerifyOptions,
2159) -> Refusal<Resolution> {
2160    let parsed = parse(did)?;
2161    let verified = verify_bytes(&parsed, log, now_ns, &options.limits)?;
2162    resolve_version(
2163        &parsed,
2164        &verified,
2165        options.seen_version_id.as_deref(),
2166        &options.query,
2167    )
2168}
2169
2170/// Steps 1 and 2 of the check order, and that some entry's state id is the
2171/// DID.
2172fn verify_bytes(parsed: &DidWebvh, log: &[u8], now_ns: i128, limits: &Limits) -> Refusal<Verified> {
2173    let entries = read_log(log, limits)?;
2174    verify_entries(parsed, entries, now_ns, limits)
2175}
2176
2177/// The rest of step 3 on a verified log: the version seen before (a
2178/// versionId, checked by the caller), the query, and that the selected
2179/// version is not the deactivated one. Then the resolution.
2180fn resolve_version(
2181    parsed: &DidWebvh,
2182    verified: &Verified,
2183    seen: Option<&str>,
2184    query: &Query,
2185) -> Refusal<Resolution> {
2186    if let Some(seen) = seen {
2187        check_seen(verified, seen)?;
2188    }
2189    let index = select(verified, query)?;
2190
2191    let last_index = verified.entries.len() - 1;
2192    let last = &verified.after[last_index];
2193    if index == last_index && last.deactivated {
2194        // The whole log verified, so its latest version is known: a caller
2195        // records it, and a log from before the deactivation is then refused.
2196        let mut error = DidWebvhError::new(DEACTIVATED, "the DID is deactivated");
2197        error.latest_version_id = verified.entries[last_index]["versionId"]
2198            .as_str()
2199            .map(str::to_string);
2200        return Err(error);
2201    }
2202    let selected = &verified.entries[index];
2203    let first = &verified.entries[0];
2204    let latest = &verified.entries[last_index];
2205    let metadata = json!({
2206        "versionId": selected["versionId"],
2207        "versionTime": selected["versionTime"],
2208        "created": first["versionTime"],
2209        "updated": latest["versionTime"],
2210        "scid": parsed.scid,
2211        "portable": last.portable,
2212        "deactivated": last.deactivated,
2213        "ttl": last.ttl.to_string(),
2214        "witness": {},
2215        "watchers": last.watchers,
2216    });
2217    Ok(Resolution {
2218        document: selected["state"].clone(),
2219        metadata,
2220        version_number: index + 1,
2221        latest_version_id: latest["versionId"].as_str().unwrap_or_default().to_string(),
2222    })
2223}
2224
2225// =============================================================================
2226// Logs for credential verification: the clock and the set of logs
2227// =============================================================================
2228
2229/// The clock a did:webvh log is checked against when it gives the keys of a
2230/// credential's issuer or of a delegation grant's issuer.
2231///
2232/// The reference resolves those logs against the time now, whatever time the
2233/// credential itself is checked at: the credential's `now` decides whether it
2234/// is within its validity window, and the log clock decides whether a log
2235/// entry is dated in the future. [`LogClock::At`] fixes the log clock
2236/// instead, for tests and replays.
2237#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2238pub enum LogClock {
2239    /// The system clock (the default, as in the reference).
2240    #[default]
2241    System,
2242    /// This time, in nanoseconds since the Unix epoch.
2243    At(i128),
2244}
2245
2246impl LogClock {
2247    /// The time this clock reads now, in nanoseconds since the Unix epoch.
2248    ///
2249    /// Errors for [`LogClock::System`] where there is no system clock
2250    /// (WebAssembly in a browser; the WASM build passes the JavaScript clock
2251    /// as [`LogClock::At`]).
2252    pub fn now_ns(self) -> Result<i128> {
2253        match self {
2254            Self::At(ns) => Ok(ns),
2255            Self::System => system_now_ns().ok_or_else(|| {
2256                CoreError::Json("there is no system clock here: give logNow".into())
2257            }),
2258        }
2259    }
2260}
2261
2262#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
2263fn system_now_ns() -> Option<i128> {
2264    use std::time::{SystemTime, UNIX_EPOCH};
2265    Some(match SystemTime::now().duration_since(UNIX_EPOCH) {
2266        Ok(after) => after.as_nanos() as i128,
2267        Err(before) => -(before.duration().as_nanos() as i128),
2268    })
2269}
2270
2271#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
2272fn system_now_ns() -> Option<i128> {
2273    None
2274}
2275
2276/// The did:webvh logs one credential verification uses, as the caller
2277/// fetched them: the issuer's, and those of delegation grant issuers.
2278///
2279/// The core keeps no state and never fetches. The caller fetches each log
2280/// from [`log_url`], gives the latest versionId it saw before for each DID
2281/// ([`LogSet::with_seen_version_id`]), and afterwards remembers the latest
2282/// versions the set reports ([`LogSet::outcomes`]), so a log later served
2283/// rolled back or forked is refused.
2284///
2285/// A log is verified the first time a verification needs it (credential
2286/// verification always uses the latest entry), against one clock read when
2287/// the set is made, and its latest state is then reused for the rest of that
2288/// verification, as the reference keeps one document per DID per
2289/// verification. Make one set per verification.
2290pub struct LogSet {
2291    now_ns: i128,
2292    limits: Limits,
2293    logs: BTreeMap<String, Vec<u8>>,
2294    seen: BTreeMap<String, String>,
2295    resolved: RefCell<BTreeMap<String, Refusal<Resolution>>>,
2296}
2297
2298impl fmt::Debug for LogSet {
2299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2300        f.debug_struct("LogSet")
2301            .field("now_ns", &self.now_ns)
2302            .field("limits", &self.limits)
2303            .field("dids", &self.logs.keys().collect::<Vec<_>>())
2304            .field("seen", &self.seen)
2305            .finish()
2306    }
2307}
2308
2309impl LogSet {
2310    /// An empty set whose logs are checked against `clock`, read now, with
2311    /// the default limits.
2312    ///
2313    /// Errors when the clock cannot be read (see [`LogClock::now_ns`]).
2314    pub fn new(clock: LogClock) -> Result<Self> {
2315        Ok(Self {
2316            now_ns: clock.now_ns()?,
2317            limits: Limits::default(),
2318            logs: BTreeMap::new(),
2319            seen: BTreeMap::new(),
2320            resolved: RefCell::new(BTreeMap::new()),
2321        })
2322    }
2323
2324    /// Check every log with these limits.
2325    pub fn with_limits(mut self, limits: Limits) -> Self {
2326        self.limits = limits;
2327        self
2328    }
2329
2330    /// The log (`did.jsonl`) of `did`, as fetched from [`log_url`].
2331    pub fn with_log(mut self, did: &str, log: Vec<u8>) -> Self {
2332        self.logs.insert(did.to_string(), log);
2333        self
2334    }
2335
2336    /// The latest versionId seen for `did` before. Its log must still
2337    /// contain it, so a log rolled back or forked since is refused.
2338    ///
2339    /// Errors when `seen` is not a did:webvh versionId.
2340    pub fn with_seen_version_id(mut self, did: &str, seen: &str) -> Result<Self> {
2341        if version_number_of(seen).is_none() {
2342            return Err(seen_version_id_error());
2343        }
2344        self.seen.insert(did.to_string(), seen.to_string());
2345        Ok(self)
2346    }
2347
2348    /// The time the logs are checked against, in nanoseconds since the Unix
2349    /// epoch.
2350    pub fn now_ns(&self) -> i128 {
2351        self.now_ns
2352    }
2353
2354    /// The limits every log is checked with.
2355    pub fn limits(&self) -> &Limits {
2356        &self.limits
2357    }
2358
2359    /// True when the set holds a log for `did`.
2360    pub fn contains(&self, did: &str) -> bool {
2361        self.logs.contains_key(did)
2362    }
2363
2364    /// The latest verified state of `did`'s log, or why the log was refused
2365    /// (a deactivated DID is `deactivated`). None when the set holds no log
2366    /// for `did`. The log is verified once; later calls reuse the answer.
2367    pub fn resolve(&self, did: &str) -> Option<Refusal<Resolution>> {
2368        if let Some(done) = self.resolved.borrow().get(did) {
2369            return Some(done.clone());
2370        }
2371        let log = self.logs.get(did)?;
2372        let mut options = VerifyOptions::new().with_limits(self.limits);
2373        // with_seen_version_id checked the form when the set was made.
2374        options.seen_version_id = self.seen.get(did).cloned();
2375        let answer = verify_log(did, log, self.now_ns, &options);
2376        self.resolved
2377            .borrow_mut()
2378            .insert(did.to_string(), answer.clone());
2379        Some(answer)
2380    }
2381
2382    /// Every log resolved so far, by DID: its latest versionId (remember it
2383    /// as the version seen for that DID), or why it was refused. A log the
2384    /// verification never needed is not listed.
2385    pub fn outcomes(&self) -> BTreeMap<String, Refusal<String>> {
2386        self.resolved
2387            .borrow()
2388            .iter()
2389            .map(|(did, answer)| {
2390                (
2391                    did.clone(),
2392                    answer
2393                        .as_ref()
2394                        .map(|r| r.latest_version_id.clone())
2395                        .map_err(Clone::clone),
2396                )
2397            })
2398            .collect()
2399    }
2400}
2401
2402// =============================================================================
2403// JSON in, JSON out (for the bindings)
2404// =============================================================================
2405
2406/// [`parse`] as JSON: `{"scid", "host", "port", "path", "url"}`, or
2407/// `{"error": {"code", "text"}}` for a refused DID.
2408pub fn parse_json(did: &str) -> Value {
2409    match parse(did) {
2410        Ok(parsed) => parsed.to_json(),
2411        Err(e) => json!({"error": {"code": e.code, "text": e.text}}),
2412    }
2413}
2414
2415pub(crate) fn base64_decode(text: &str, name: &str) -> Result<Vec<u8>> {
2416    use base64::{engine::general_purpose::STANDARD, Engine};
2417    STANDARD
2418        .decode(text)
2419        .map_err(|_| CoreError::Json(format!("{name} must be standard base64")))
2420}
2421
2422/// The log bytes of a request: `text_name` (the log as text) or `b64_name`
2423/// (its bytes in base64, for a log that is not UTF-8), exactly one.
2424fn log_bytes(request: &Map<String, Value>, text_name: &str, b64_name: &str) -> Result<Vec<u8>> {
2425    match (request.get(text_name), request.get(b64_name)) {
2426        (Some(Value::String(text)), None) => Ok(text.as_bytes().to_vec()),
2427        (None, Some(Value::String(b64))) => base64_decode(b64, b64_name),
2428        _ => Err(CoreError::Json(format!(
2429            "give the log as {text_name} (text) or {b64_name} (base64), exactly one"
2430        ))),
2431    }
2432}
2433
2434pub(crate) fn request_object<'a>(
2435    request: &'a Value,
2436    allowed: &[&str],
2437) -> Result<&'a Map<String, Value>> {
2438    let obj = request
2439        .as_object()
2440        .ok_or_else(|| CoreError::Json("the request must be a JSON object".into()))?;
2441    if let Some(name) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
2442        return Err(CoreError::Json(format!(
2443            "the request holds an unknown member {:?}",
2444            name.chars().take(40).collect::<String>()
2445        )));
2446    }
2447    Ok(obj)
2448}
2449
2450fn request_text<'a>(obj: &'a Map<String, Value>, name: &str) -> Result<&'a str> {
2451    obj.get(name)
2452        .and_then(Value::as_str)
2453        .ok_or_else(|| CoreError::Json(format!("{name} must be a string")))
2454}
2455
2456/// [`verify_log`] as JSON. The request is `{"did", "log" or "logB64", "now",
2457/// "options"}`: `log` is the log as text, `logB64` its bytes in base64 (for a
2458/// log that is not UTF-8), `now` a protocol time, and `options` (optional)
2459/// as [`VerifyOptions::from_json`] reads it.
2460///
2461/// Returns `{"document", "metadata", "versionNumber", "latestVersionId"}`,
2462/// or `{"error": {"code", "text", "entry"}}` when the DID or the log is
2463/// refused. A malformed request (a missing member, two queries, bad limits,
2464/// a seenVersionId that is not a versionId) is an `Err`.
2465///
2466/// The checks run in the reference's order, so a request that has both a
2467/// refusal and a mistake gives the same answer in every language: the
2468/// request, `now` and the limits; then the DID; then the query (at most one,
2469/// of the right type); then the log; and only then the form of the version
2470/// seen before, and the rest of step 3.
2471pub fn verify_log_json(request: &Value) -> Result<Value> {
2472    let obj = request_object(request, &["did", "log", "logB64", "now", "options"])?;
2473    let did = request_text(obj, "did")?;
2474    let log = log_bytes(obj, "log", "logB64")?;
2475    let now_ns = time::parse_protocol_time_ns(request_text(obj, "now")?)?;
2476    let empty = Map::new();
2477    let options = match obj.get("options") {
2478        None | Some(Value::Null) => &empty,
2479        Some(Value::Object(options)) => options,
2480        Some(_) => return Err(CoreError::Json("options must be a JSON object".into())),
2481    };
2482    let limits = match options.get("limits").filter(|v| !v.is_null()) {
2483        Some(v) => Limits::from_json(v)?,
2484        None => Limits::default(),
2485    };
2486    let refused = |e: DidWebvhError| json!({"error": e.to_json()});
2487    let parsed = match parse(did) {
2488        Ok(parsed) => parsed,
2489        Err(e) => return Ok(refused(e)),
2490    };
2491    let (query, seen) = read_query(options)?;
2492    let verified = match verify_bytes(&parsed, &log, now_ns, &limits) {
2493        Ok(verified) => verified,
2494        Err(e) => return Ok(refused(e)),
2495    };
2496    if seen
2497        .as_deref()
2498        .is_some_and(|s| version_number_of(s).is_none())
2499    {
2500        return Err(seen_version_id_error());
2501    }
2502    Ok(
2503        match resolve_version(&parsed, &verified, seen.as_deref(), &query) {
2504            Ok(resolution) => resolution.to_json(),
2505            Err(e) => refused(e),
2506        },
2507    )
2508}
2509
2510/// The request members every verify request shares for the delegation
2511/// chain and the did:webvh logs (see [`read_chain_request`]).
2512pub(crate) const CHAIN_REQUEST_MEMBERS: [&str; 11] = [
2513    "now",
2514    "clockSkewSeconds",
2515    "trustedRoots",
2516    "requirePostQuantum",
2517    "grantKeys",
2518    "grantMldsa44Keys",
2519    "grantLogs",
2520    "grantLogsB64",
2521    "grantSeenVersionIds",
2522    "limits",
2523    "logNow",
2524];
2525
2526/// The chain and log members of a verify request, read.
2527pub(crate) struct ChainRequest {
2528    pub(crate) now: String,
2529    pub(crate) skew: i64,
2530    pub(crate) roots: Option<Vec<String>>,
2531    pub(crate) require_pq: bool,
2532    pub(crate) grant_keys: Option<BTreeMap<String, Vec<u8>>>,
2533    pub(crate) grant_mldsa_keys: Option<BTreeMap<String, Vec<u8>>>,
2534    /// The grant issuers' logs and versions seen, with the limits and the
2535    /// clock. The did:webvh credential request adds the issuer's log.
2536    pub(crate) logs: LogSet,
2537}
2538
2539fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
2540    obj.get(name).filter(|v| !v.is_null())
2541}
2542
2543/// A JSON object of DID to text, or None when absent.
2544fn text_map<'a>(
2545    obj: &'a Map<String, Value>,
2546    name: &str,
2547    what: &str,
2548) -> Result<Option<Vec<(&'a String, &'a str)>>> {
2549    let bad = || CoreError::Json(format!("{name} must be a JSON object of DID to {what}"));
2550    match present(obj, name) {
2551        None => Ok(None),
2552        Some(Value::Object(map)) => map
2553            .iter()
2554            .map(|(did, v)| v.as_str().map(|t| (did, t)).ok_or_else(bad))
2555            .collect::<Result<Vec<_>>>()
2556            .map(Some),
2557        Some(_) => Err(bad()),
2558    }
2559}
2560
2561/// A JSON object of DID to base64 key, decoded.
2562fn key_map(obj: &Map<String, Value>, name: &str) -> Result<Option<BTreeMap<String, Vec<u8>>>> {
2563    match text_map(obj, name, "base64 key")? {
2564        None => Ok(None),
2565        Some(items) => items
2566            .into_iter()
2567            .map(|(did, key)| Ok((did.clone(), base64_decode(key, &format!("a {name} key"))?)))
2568            .collect::<Result<_>>()
2569            .map(Some),
2570    }
2571}
2572
2573/// Read the members of a verify request that every entry shares:
2574///
2575/// - `now` (a protocol time, required) and `clockSkewSeconds` (0 to 120,
2576///   default 0): the credential's own clock;
2577/// - `trustedRoots` (optional): the DIDs a delegation chain must start from;
2578///   without it a credential carrying a chain is refused;
2579/// - `requirePostQuantum` (default false);
2580/// - `grantKeys` (optional): Ed25519 keys (base64) of grant issuers that are
2581///   not did:key, by DID. They resolve grant signatures only and never make
2582///   a DID a trusted root;
2583/// - `grantMldsa44Keys` (optional): ML-DSA-44 keys (base64) of grant
2584///   issuers, by DID;
2585/// - `grantLogs` / `grantLogsB64` (optional): the `did.jsonl` of did:webvh
2586///   grant issuers, by DID, as text or base64 (a DID in at most one);
2587/// - `grantSeenVersionIds` (optional): the latest versionId seen before for
2588///   each of those DIDs;
2589/// - `limits` (optional): as [`Limits::from_json`], for every log;
2590/// - `logNow` (optional): a protocol time to check the logs against, for
2591///   tests and replays. Without it the logs are checked against `clock`.
2592pub(crate) fn read_chain_request(
2593    obj: &Map<String, Value>,
2594    clock: LogClock,
2595) -> Result<ChainRequest> {
2596    let now = request_text(obj, "now")?.to_string();
2597    time::parse_protocol_time_ns(&now)?;
2598    let skew = match present(obj, "clockSkewSeconds") {
2599        None => 0,
2600        Some(v) => time::clock_skew_from_json(v)?,
2601    };
2602    let roots = match present(obj, "trustedRoots") {
2603        None => None,
2604        Some(v) => Some(
2605            string_list(v)
2606                .ok_or_else(|| CoreError::Json("trustedRoots must be a list of strings".into()))?
2607                .into_iter()
2608                .map(str::to_string)
2609                .collect(),
2610        ),
2611    };
2612    let require_pq = match present(obj, "requirePostQuantum") {
2613        None => false,
2614        Some(Value::Bool(b)) => *b,
2615        Some(_) => {
2616            return Err(CoreError::Json(
2617                "requirePostQuantum must be true or false".into(),
2618            ))
2619        }
2620    };
2621    let grant_keys = key_map(obj, "grantKeys")?;
2622    let grant_mldsa_keys = key_map(obj, "grantMldsa44Keys")?;
2623    let clock = match present(obj, "logNow") {
2624        None => clock,
2625        Some(v) => LogClock::At(time::parse_protocol_time_ns(
2626            v.as_str()
2627                .ok_or_else(|| CoreError::Json("logNow must be a protocol time".into()))?,
2628        )?),
2629    };
2630    let mut logs = LogSet::new(clock)?;
2631    if let Some(limits) = present(obj, "limits") {
2632        logs = logs.with_limits(Limits::from_json(limits)?);
2633    }
2634    let texts = text_map(obj, "grantLogs", "log text")?.unwrap_or_default();
2635    let b64s = text_map(obj, "grantLogsB64", "base64 log")?.unwrap_or_default();
2636    for (did, log) in texts
2637        .into_iter()
2638        .map(|(did, text)| Ok((did, text.as_bytes().to_vec())))
2639        .chain(
2640            b64s.into_iter()
2641                .map(|(did, b64)| Ok((did, base64_decode(b64, "a grantLogsB64 log")?))),
2642        )
2643        .collect::<Result<Vec<_>>>()?
2644    {
2645        if !is_did_webvh(did) {
2646            return Err(CoreError::Json(
2647                "grantLogs holds a DID that is not a did:webvh DID".into(),
2648            ));
2649        }
2650        if logs.contains(did) {
2651            return Err(CoreError::Json(
2652                "give each grant issuer's log once, in grantLogs or grantLogsB64".into(),
2653            ));
2654        }
2655        logs = logs.with_log(did, log);
2656    }
2657    for (did, seen) in text_map(obj, "grantSeenVersionIds", "versionId")?.unwrap_or_default() {
2658        logs = logs.with_seen_version_id(did, seen)?;
2659    }
2660    Ok(ChainRequest {
2661        now,
2662        skew,
2663        roots,
2664        require_pq,
2665        grant_keys,
2666        grant_mldsa_keys,
2667        logs,
2668    })
2669}
2670
2671/// The grant logs a verification resolved, as two JSON objects:
2672/// `grantVersionIds` (DID to latest versionId) and `grantLogErrors` (DID to
2673/// `{"code", "text", "entry"}`).
2674pub(crate) fn grant_log_json(outcomes: &BTreeMap<String, Refusal<String>>) -> (Value, Value) {
2675    let mut versions = Map::new();
2676    let mut errors = Map::new();
2677    for (did, outcome) in outcomes {
2678        match outcome {
2679            Ok(version) => {
2680                versions.insert(did.clone(), Value::String(version.clone()));
2681            }
2682            Err(e) => {
2683                errors.insert(did.clone(), e.to_json());
2684            }
2685        }
2686    }
2687    (Value::Object(versions), Value::Object(errors))
2688}
2689
2690/// [`crate::credentials::verify_with_did_webvh_log`] as JSON, with the logs
2691/// checked against the system clock (see [`verify_credential_json_with_clock`]).
2692pub fn verify_credential_json(request: &Value) -> Result<Value> {
2693    verify_credential_json_with_clock(request, LogClock::System)
2694}
2695
2696/// [`crate::credentials::verify_with_did_webvh_log`] as JSON. The request is
2697/// `{"credential", "issuerLog" or "issuerLogB64", "seenVersionId"}` plus the
2698/// members [`read_chain_request`] reads (`now`, `clockSkewSeconds`,
2699/// `trustedRoots`, `requirePostQuantum`, `grantKeys`, `grantMldsa44Keys`,
2700/// `grantLogs`, `grantLogsB64`, `grantSeenVersionIds`, `limits`, `logNow`):
2701///
2702/// - `credential`: the credential (a JSON object) whose issuer is a
2703///   did:webvh DID;
2704/// - `issuerLog` / `issuerLogB64`: the issuer's `did.jsonl`, fetched by the
2705///   caller from [`log_url`], as text or base64, exactly one;
2706/// - `seenVersionId` (optional): the latest versionId seen before for the
2707///   issuer.
2708///
2709/// Every log is checked against `logNow` when the request gives one, else
2710/// against `clock` (the system clock for [`verify_credential_json`]), never
2711/// against the credential's `now`.
2712///
2713/// Returns `{"proofValid", "timeValid", "chainValid", "valid",
2714/// "chainReason", "issuerVersionId", "issuerLogError", "grantVersionIds",
2715/// "grantLogErrors"}`: `issuerVersionId` is the issuer log's latest
2716/// versionId (remember it as the version seen) and `issuerLogError` is null,
2717/// or `{"code", "text", "entry"}` when the log was refused (the proof is then
2718/// not valid); `grantVersionIds` and `grantLogErrors` say the same, by DID,
2719/// for the grant issuers' logs the chain needed.
2720pub fn verify_credential_json_with_clock(request: &Value, clock: LogClock) -> Result<Value> {
2721    let mut allowed = vec!["credential", "issuerLog", "issuerLogB64", "seenVersionId"];
2722    allowed.extend(CHAIN_REQUEST_MEMBERS);
2723    let obj = request_object(request, &allowed)?;
2724    let credential = obj
2725        .get("credential")
2726        .filter(|c| c.is_object())
2727        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
2728    let log = log_bytes(obj, "issuerLog", "issuerLogB64")?;
2729    let request = read_chain_request(obj, clock)?;
2730    let issuer = crate::credentials::issuer_did(credential)
2731        .filter(|i| is_did_webvh(i))
2732        .ok_or_else(|| {
2733            CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
2734        })?;
2735    if request.logs.contains(issuer) {
2736        return Err(CoreError::Json(
2737            "give the issuer's log once, as issuerLog or issuerLogB64".into(),
2738        ));
2739    }
2740    let mut logs = request.logs.with_log(issuer, log);
2741    if let Some(seen) = present(obj, "seenVersionId") {
2742        let seen = seen
2743            .as_str()
2744            .ok_or_else(|| CoreError::Json("seenVersionId must be a string".into()))?;
2745        logs = logs.with_seen_version_id(issuer, seen)?;
2746    }
2747    let chain = crate::delegation::ChainOptions {
2748        trusted_roots: request.roots.as_deref(),
2749        grant_keys: request.grant_keys.as_ref(),
2750        mldsa_keys: request.grant_mldsa_keys.as_ref(),
2751        require_pq: request.require_pq,
2752        ..Default::default()
2753    };
2754    let outcome = crate::credentials::verify_with_did_webvh_log(
2755        credential,
2756        &logs,
2757        &request.now,
2758        request.skew,
2759        &chain,
2760    )?;
2761    let r = outcome.result;
2762    let (grant_versions, grant_errors) = grant_log_json(&outcome.grant_logs);
2763    Ok(json!({
2764        "proofValid": r.proof_valid,
2765        "timeValid": r.time_valid,
2766        "chainValid": r.chain_valid,
2767        "valid": r.is_valid(),
2768        "chainReason": outcome.chain_reason,
2769        "issuerVersionId": outcome.log.as_ref().ok(),
2770        "issuerLogError": outcome.log.as_ref().err().map(DidWebvhError::to_json),
2771        "grantVersionIds": grant_versions,
2772        "grantLogErrors": grant_errors,
2773    }))
2774}
2775
2776#[cfg(test)]
2777mod tests {
2778    use super::*;
2779
2780    #[test]
2781    fn depth_scan_counts_brackets_outside_strings() {
2782        let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
2783        assert!(!json_too_deep(nested(64).as_bytes(), 64));
2784        assert!(json_too_deep(nested(65).as_bytes(), 64));
2785        // Brackets inside strings, escaped quotes included, do not count.
2786        let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
2787        assert!(!json_too_deep(quoted.as_bytes(), 64));
2788        // A string with no closing quote runs to the end.
2789        assert!(!json_too_deep(b"{\"a\":\"[[[[", 2));
2790    }
2791
2792    #[test]
2793    fn reader_reports_problems_where_python_does() {
2794        let read = |s: &str| read_json_line(s.as_bytes());
2795        assert_eq!(read(r#"{"a":1,"a":2}"#).unwrap_err(), JsonProblem::Repeated);
2796        // A repeated name in an object still open does not count before a
2797        // number out of range later in it.
2798        assert_eq!(
2799            read(r#"{"a":1,"a":2,"b":99999999999999999}"#).unwrap_err(),
2800            JsonProblem::OutOfRange
2801        );
2802        assert_eq!(
2803            read(r#"{"x":{"a":1,"a":2},"b":1e999}"#).unwrap_err(),
2804            JsonProblem::Repeated
2805        );
2806        assert_eq!(
2807            read(r#"{"a":1,"a":2,"b":tru}"#).unwrap_err(),
2808            JsonProblem::Invalid
2809        );
2810        // The integer part is read (and range-checked) before a bad exponent.
2811        assert_eq!(
2812            read(r#"{"a":99999999999999999e}"#).unwrap_err(),
2813            JsonProblem::OutOfRange
2814        );
2815        assert_eq!(read(r#"{"a":1e}"#).unwrap_err(), JsonProblem::Invalid);
2816        assert_eq!(read(r#"{"a":NaN}"#).unwrap_err(), JsonProblem::Invalid);
2817        assert_eq!(
2818            read(r#"{"a":-Infinity}"#).unwrap_err(),
2819            JsonProblem::Invalid
2820        );
2821        assert_eq!(read(r#"{"a":01}"#).unwrap_err(), JsonProblem::Invalid);
2822        assert_eq!(read(r#"{"a":[1,]}"#).unwrap_err(), JsonProblem::Invalid);
2823        assert_eq!(read(r#"{"a":1,}"#).unwrap_err(), JsonProblem::Invalid);
2824        assert_eq!(read("{\"a\":\"\t\"}").unwrap_err(), JsonProblem::Invalid);
2825        assert_eq!(read(r#"{"a":"\x"}"#).unwrap_err(), JsonProblem::Invalid);
2826        assert_eq!(read(r#"{}{}"#).unwrap_err(), JsonProblem::Invalid);
2827        assert_eq!(
2828            read(r#"{"a":9007199254740991}"#).unwrap().0["a"],
2829            9007199254740991i64
2830        );
2831        assert_eq!(
2832            read(r#"{"a":-9007199254740992}"#).unwrap_err(),
2833            JsonProblem::OutOfRange
2834        );
2835        assert_eq!(
2836            read(r#"{"a":9007199254740992.0}"#).unwrap_err(),
2837            JsonProblem::OutOfRange
2838        );
2839        // Lone surrogates are remembered; two different ones are two names.
2840        assert!(read(r#"{"a":"\ud800"}"#).unwrap().1);
2841        assert!(read(r#"{"\ud800":1,"\udc00":2}"#).unwrap().1);
2842        assert_eq!(
2843            read(r#"{"\ud800":1,"\ud800":2}"#).unwrap_err(),
2844            JsonProblem::Repeated
2845        );
2846        // A pair is one character, and the same name as the raw character.
2847        let (v, lone) = read(r#"{"a":"😀"}"#).unwrap();
2848        assert!(!lone);
2849        assert_eq!(v["a"], "\u{1F600}");
2850        assert_eq!(
2851            read("{\"\u{1F600}\":1,\"\\ud83d\\ude00\":2}").unwrap_err(),
2852            JsonProblem::Repeated
2853        );
2854        assert_eq!(
2855            read(r#"{"a":"a","a":1}"#).unwrap_err(),
2856            JsonProblem::Repeated
2857        );
2858    }
2859
2860    #[test]
2861    fn options_from_json() {
2862        assert!(
2863            VerifyOptions::from_json(&json!({"versionId": "1-x", "versionNumber": 1})).is_err()
2864        );
2865        assert!(VerifyOptions::from_json(&json!({"versionNumber": 1.0})).is_err());
2866        assert!(VerifyOptions::from_json(&json!({"versionNumber": true})).is_err());
2867        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "01-x"})).is_err());
2868        assert!(VerifyOptions::from_json(&json!({"seenVersionId": "1"})).is_err());
2869        assert!(VerifyOptions::from_json(&json!({"other": 1})).is_err());
2870        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 0}})).is_err());
2871        assert!(VerifyOptions::from_json(&json!({"limits": {"maxBytes": 5242881}})).is_err());
2872        assert!(VerifyOptions::from_json(&json!({"limits": {"maxProofs": true}})).is_err());
2873        assert!(VerifyOptions::from_json(&json!({"limits": {"maxx": 1}})).is_err());
2874        let o = VerifyOptions::from_json(
2875            &json!({"versionId": null, "versionTime": "x", "limits": {"maxEntries": 2}}),
2876        )
2877        .unwrap();
2878        assert_eq!(o.query(), &Query::VersionTime("x".into()));
2879        assert_eq!(o.limits().max_entries(), 2);
2880        assert_eq!(o.limits().max_bytes(), 1024 * 1024);
2881        assert_eq!(
2882            VerifyOptions::from_json(&json!({"versionNumber": u64::MAX}))
2883                .unwrap()
2884                .query(),
2885            &Query::VersionNumber(i64::MAX)
2886        );
2887    }
2888
2889    /// The `create` log of the shared vector, with its proofValue's R
2890    /// replaced by `r`.
2891    fn create_log_with_r(r: [u8; 32]) -> (String, String) {
2892        let path = concat!(
2893            env!("CARGO_MANIFEST_DIR"),
2894            "/../../test-vectors/did-webvh/vector.json"
2895        );
2896        let v: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
2897        let case = v["logs"]
2898            .as_array()
2899            .unwrap()
2900            .iter()
2901            .find(|c| c["name"] == "create")
2902            .unwrap();
2903        let log = case["log"].as_str().unwrap();
2904        let entry: Value = serde_json::from_str(log.trim_end()).unwrap();
2905        let value = entry["proof"][0]["proofValue"].as_str().unwrap();
2906        let mut signature = bs58::decode(&value[1..]).into_vec().unwrap();
2907        signature[..32].copy_from_slice(&r);
2908        let changed = format!("z{}", bs58::encode(signature).into_string());
2909        (
2910            case["did"].as_str().unwrap().to_string(),
2911            log.replace(value, &changed),
2912        )
2913    }
2914
2915    fn refusal(did: &str, log: &str) -> DidWebvhError {
2916        let now = time::parse_protocol_time_ns("2026-11-30T00:00:00Z").unwrap();
2917        verify_log(did, log.as_bytes(), now, &VerifyOptions::new()).unwrap_err()
2918    }
2919
2920    #[test]
2921    fn an_r_off_the_curve_fails_at_verification() {
2922        // A y below p (a canonical encoding) that names no point on the curve.
2923        let off_curve = (2u8..=255)
2924            .map(|y| {
2925                let mut r = [0u8; 32];
2926                r[0] = y;
2927                r
2928            })
2929            .find(|r| ed25519_dalek::VerifyingKey::from_bytes(r).is_err())
2930            .expect("a y with no point");
2931        assert!(keys::is_canonical_point_encoding(&off_curve));
2932        // The form check lets it through, as the reference's does ...
2933        let mut signature = vec![0u8; 64];
2934        signature[..32].copy_from_slice(&off_curve);
2935        let value = Value::String(format!("z{}", bs58::encode(&signature).into_string()));
2936        assert!(strict_signature(&value).is_some());
2937        // ... and the proof then does not verify.
2938        let (did, log) = create_log_with_r(off_curve);
2939        let e = refusal(&did, &log);
2940        assert_eq!(
2941            (e.code, e.text, e.entry),
2942            (INVALID_DID, "a log entry proof does not verify", Some(1))
2943        );
2944    }
2945
2946    #[test]
2947    fn a_small_order_or_non_canonical_r_is_not_a_signature() {
2948        for hex in SMALL_ORDER_ENCODINGS {
2949            let mut r = [0u8; 32];
2950            for (i, b) in r.iter_mut().enumerate() {
2951                *b = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap();
2952            }
2953            let (did, log) = create_log_with_r(r);
2954            let e = refusal(&did, &log);
2955            assert_eq!(
2956                (e.text, e.entry),
2957                (
2958                    "a log entry proof's proofValue is not an Ed25519 signature",
2959                    Some(1)
2960                ),
2961                "{hex}"
2962            );
2963        }
2964        // y >= p that is not of small order (y = p + 3).
2965        let mut r = [0xffu8; 32];
2966        r[0] = 0xf0;
2967        r[31] = 0x7f;
2968        let (did, log) = create_log_with_r(r);
2969        assert_eq!(
2970            refusal(&did, &log).text,
2971            "a log entry proof's proofValue is not an Ed25519 signature"
2972        );
2973    }
2974
2975    #[test]
2976    fn prefix_keeps_its_colon() {
2977        assert!(is_did_webvh("did:webvh:x"));
2978        assert!(!is_did_webvh("did:web:x"));
2979        assert!(!is_did_webvh("did:webvhx:x"));
2980        assert_eq!(
2981            parse("did:web:example.com").unwrap_err().text,
2982            "not a did:webvh DID"
2983        );
2984    }
2985}