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