Skip to main content

vouch_core/
robotics_json.rs

1//! JSON facades for the robotics primitives.
2//!
3//! The robotics core ([`crate::robotics`]) works in typed Rust. These facades
4//! present every capability as JSON-in / JSON-out with keys passed as bytes and
5//! binary fields carried as multibase strings, so the UniFFI, WASM, and C-ABI
6//! wrappers expose robotics to Swift, Kotlin/JVM, .NET, C/C++, and the browser
7//! with one shared implementation instead of re-deriving the plumbing per layer.
8//!
9//! Convention: a verifier that returns "no subject/session" yields the JSON
10//! literal `null`; callers test for it.
11//!
12//! Input rules shared by every facade:
13//!
14//! * A field that is absent or JSON `null` means "not given". A field that is
15//!   present with the wrong type (a number where a string belongs, a string
16//!   where a number or a list belongs) is an error, never silently dropped.
17//! * Every JSON input is at most [`MAX_INPUT_BYTES`] bytes and no list in it
18//!   holds more than [`MAX_LIST_ITEMS`] items.
19//! * Verifiers that check a validity window take the verifier's clock. A
20//!   request's `now` must be a protocol time; without one, the facade uses the
21//!   `host_now` (or `now_iso`) the wrapper passes, which the WASM, UniFFI and C
22//!   ABI wrappers fill from the host clock. The core never treats a missing
23//!   clock as "skip the window check".
24
25#[allow(unused_imports)]
26use crate::prelude::*;
27
28use crate::collections::HashSet;
29use serde_json::{json, Value};
30
31use crate::error::{CoreError, Result};
32use crate::robotics as r;
33use crate::robotics_verify::Keys;
34
35/// The largest JSON input any robotics facade accepts, in bytes (1 MiB).
36pub const MAX_INPUT_BYTES: usize = 1024 * 1024;
37/// The most items any one JSON list in a facade input may hold.
38pub const MAX_LIST_ITEMS: usize = 10_000;
39
40/// The most items one list may hold in a log or history facade (a black-box
41/// log, a fork check over an agent's whole history).
42pub const MAX_LONG_LIST_ITEMS: usize = 1_000_000;
43
44fn check_lists(v: &Value) -> Result<()> {
45    check_lists_capped(v, MAX_LIST_ITEMS)
46}
47
48fn check_lists_capped(v: &Value, cap: usize) -> Result<()> {
49    match v {
50        Value::Array(a) => {
51            if a.len() > cap {
52                return Err(CoreError::Json(format!(
53                    "json: a list holds more than {cap} items"
54                )));
55            }
56            a.iter().try_for_each(|x| check_lists_capped(x, cap))
57        }
58        Value::Object(o) => o.values().try_for_each(|x| check_lists_capped(x, cap)),
59        _ => Ok(()),
60    }
61}
62
63/// The hard ceiling a host may raise the log input limit to (1 GiB).
64pub const LOG_CEILING_BYTES: usize = 1 << 30;
65/// The hard ceiling a host may raise the log list limit to.
66pub const LOG_CEILING_ITEMS: usize = 50_000_000;
67/// The ceiling in WASM, where all memory is at most 4 GiB: a 1 GiB log
68/// parsed there could exhaust it.
69pub const WASM_LOG_CEILING_BYTES: usize = 256 << 20;
70/// The list ceiling in WASM.
71pub const WASM_LOG_CEILING_ITEMS: usize = 5_000_000;
72
73/// The host's limits for the log and history facades (the black-box,
74/// safety and perception log checks, the fork check, and their segment
75/// entry points): the largest input in bytes and the most items in one
76/// list. The default is 64 MiB and 1,000,000 items. An operator may raise
77/// them (vouch-policy.json `robotics.maxInputBytes` and `robotics.maxItems`)
78/// up to [`LOG_CEILING_BYTES`] and [`LOG_CEILING_ITEMS`]; a longer log is
79/// checked in segments, whose memory does not grow with the log.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct LogLimits {
82    pub max_bytes: usize,
83    pub max_items: usize,
84}
85
86impl Default for LogLimits {
87    fn default() -> Self {
88        Self::DEFAULT
89    }
90}
91
92impl LogLimits {
93    /// 64 MiB and 1,000,000 items.
94    pub const DEFAULT: LogLimits = LogLimits {
95        max_bytes: r::MAX_LOG_BYTES,
96        max_items: MAX_LONG_LIST_ITEMS,
97    };
98
99    /// The host's limits, refused above the hard ceiling.
100    pub fn new(max_bytes: u64, max_items: u64) -> Result<Self> {
101        Self::within(
102            max_bytes,
103            max_items,
104            LOG_CEILING_BYTES,
105            LOG_CEILING_ITEMS,
106            "hard",
107        )
108    }
109
110    /// The host's limits in WASM, refused above the lower WASM ceiling.
111    pub fn new_wasm(max_bytes: u64, max_items: u64) -> Result<Self> {
112        Self::within(
113            max_bytes,
114            max_items,
115            WASM_LOG_CEILING_BYTES,
116            WASM_LOG_CEILING_ITEMS,
117            "WASM",
118        )
119    }
120
121    fn within(
122        max_bytes: u64,
123        max_items: u64,
124        ceiling_bytes: usize,
125        ceiling_items: usize,
126        which: &str,
127    ) -> Result<Self> {
128        let why = if which == "WASM" {
129            " (WASM memory is at most 4 GiB, so a larger log is not safe to load there)"
130        } else {
131            ""
132        };
133        if max_bytes == 0 {
134            return Err(CoreError::Json("maxInputBytes must be at least 1".into()));
135        }
136        if max_items == 0 {
137            return Err(CoreError::Json("maxItems must be at least 1".into()));
138        }
139        if max_bytes > ceiling_bytes as u64 {
140            return Err(CoreError::Json(format!(
141                "maxInputBytes is above the {which} ceiling of {ceiling_bytes} bytes{why}; check a longer log in segments"
142            )));
143        }
144        if max_items > ceiling_items as u64 {
145            return Err(CoreError::Json(format!(
146                "maxItems is above the {which} ceiling of {ceiling_items} items{why}; check a longer log in segments"
147            )));
148        }
149        Ok(Self {
150            max_bytes: max_bytes as usize,
151            max_items: max_items as usize,
152        })
153    }
154}
155
156/// Parse a log or history input: up to `limits.max_bytes` and lists of up
157/// to `limits.max_items` items. The checks these facades run are linear or
158/// n log n in the input.
159fn parse_long_with(s: &str, limits: LogLimits) -> Result<Value> {
160    if s.len() > limits.max_bytes {
161        return Err(CoreError::Json(format!(
162            "json: input is larger than {} bytes",
163            limits.max_bytes
164        )));
165    }
166    crate::nesting::check_text(s.as_bytes())?;
167    let v: Value = serde_json::from_str(s).map_err(|e| CoreError::Json(format!("json: {e}")))?;
168    check_lists_capped(&v, limits.max_items)?;
169    Ok(v)
170}
171
172/// Parse a facade input. Inputs over [`MAX_INPUT_BYTES`], or holding a list
173/// with more than [`MAX_LIST_ITEMS`] items, are refused before any work is done
174/// on them, so a caller cannot make the WASM, C ABI or UniFFI layer spend
175/// unbounded time or memory on one call.
176fn parse(s: &str) -> Result<Value> {
177    if s.len() > MAX_INPUT_BYTES {
178        return Err(CoreError::Json(format!(
179            "json: input is larger than {MAX_INPUT_BYTES} bytes"
180        )));
181    }
182    crate::nesting::check_text(s.as_bytes())?;
183    let v: Value = serde_json::from_str(s).map_err(|e| CoreError::Json(format!("json: {e}")))?;
184    check_lists(&v)?;
185    Ok(v)
186}
187// Field readers. A field that is absent or JSON null reads as "not given"; a
188// field that is present with the wrong type is an error, never silently
189// dropped (a dropped `forceN: "5000"` or `zone: 7` would skip a safety check).
190fn wrong_type(k: &str, want: &str) -> CoreError {
191    CoreError::Json(format!("{k} must be {want}"))
192}
193fn present<'a>(v: &'a Value, k: &str) -> Option<&'a Value> {
194    v.get(k).filter(|x| !x.is_null())
195}
196fn gs(v: &Value, k: &str) -> Result<String> {
197    Ok(gos(v, k)?.unwrap_or_default())
198}
199fn gos(v: &Value, k: &str) -> Result<Option<String>> {
200    match present(v, k) {
201        None => Ok(None),
202        Some(Value::String(s)) => Ok(Some(s.clone())),
203        Some(_) => Err(wrong_type(k, "a string")),
204    }
205}
206fn gof(v: &Value, k: &str) -> Result<Option<f64>> {
207    match present(v, k) {
208        None => Ok(None),
209        Some(x) => match x.as_f64() {
210            Some(n) if x.is_number() && n.is_finite() => Ok(Some(n)),
211            _ => Err(wrong_type(k, "a number")),
212        },
213    }
214}
215fn gbool(v: &Value, k: &str) -> Result<bool> {
216    match present(v, k) {
217        None => Ok(false),
218        Some(Value::Bool(b)) => Ok(*b),
219        Some(_) => Err(wrong_type(k, "true or false")),
220    }
221}
222fn goarr(v: &Value, k: &str) -> Result<Option<Vec<Value>>> {
223    match present(v, k) {
224        None => Ok(None),
225        Some(Value::Array(a)) => Ok(Some(a.clone())),
226        Some(_) => Err(wrong_type(k, "a list")),
227    }
228}
229fn garr(v: &Value, k: &str) -> Result<Vec<Value>> {
230    Ok(goarr(v, k)?.unwrap_or_default())
231}
232fn strs_of(a: &[Value], k: &str) -> Result<Vec<String>> {
233    a.iter()
234        .map(|e| {
235            e.as_str()
236                .map(String::from)
237                .ok_or_else(|| wrong_type(k, "a list of strings"))
238        })
239        .collect()
240}
241fn gstrs(v: &Value, k: &str) -> Result<Vec<String>> {
242    Ok(gostrs(v, k)?.unwrap_or_default())
243}
244fn gostrs(v: &Value, k: &str) -> Result<Option<Vec<String>>> {
245    match goarr(v, k)? {
246        None => Ok(None),
247        Some(a) => Ok(Some(strs_of(&a, k)?)),
248    }
249}
250fn gwindows(v: &Value, k: &str) -> Result<Option<Vec<r::ShiftWindow>>> {
251    match goarr(v, k)? {
252        None => Ok(None),
253        Some(a) => a
254            .iter()
255            .map(|w| {
256                if !w.is_object() {
257                    return Err(wrong_type(k, "a list of {start, end} windows"));
258                }
259                Ok(r::ShiftWindow {
260                    start: gs(w, "start")?,
261                    end: gs(w, "end")?,
262                })
263            })
264            .collect::<Result<Vec<_>>>()
265            .map(Some),
266    }
267}
268/// A physical action object: `{forceN?, speedMps?, nearHumans?, zone?,
269/// timeHm?}`. A present field of the wrong type is an error.
270fn action_from(a: &Value) -> Result<r::PhysicalAction> {
271    let o = a
272        .as_object()
273        .ok_or_else(|| CoreError::Json("action must be an object".into()))?;
274    const ACTION_KEYS: [&str; 5] = ["forceN", "speedMps", "nearHumans", "zone", "timeHm"];
275    if let Some(k) = o.keys().find(|k| !ACTION_KEYS.contains(&k.as_str())) {
276        return Err(CoreError::Json(format!("unknown action field {k:?}")));
277    }
278    Ok(r::PhysicalAction {
279        force_n: gof(a, "forceN")?,
280        speed_mps: gof(a, "speedMps")?,
281        near_humans: gbool(a, "nearHumans")?,
282        zone: gos(a, "zone")?,
283        time_hm: gos(a, "timeHm")?,
284    })
285}
286/// The verifier's clock for a request: its `now` when the caller gives one (it
287/// must be a string; the core refuses an empty or malformed time), else
288/// `host_now`, the host clock the wrapper supplies.
289fn now_or(p: &Value, host_now: &str) -> Result<String> {
290    Ok(gos(p, "now")?.unwrap_or_else(|| host_now.to_string()))
291}
292fn opt_obj(s: Option<&str>) -> Result<Option<Value>> {
293    match s {
294        Some(t) if !t.is_empty() && t != "null" => Ok(Some(parse(t)?)),
295        _ => Ok(None),
296    }
297}
298/// The key source for a facade call that checks an AUTHORITY credential (kill
299/// switch, lease, grant, scope, ...): with `issuer_did`, the key is trusted for
300/// that DID only; without it, the key is a bare key, which only a did:key
301/// issuer (whose DID carries that same key) accepts. An empty key is no key
302/// source at all: the credential then verifies only when its did:key issuer is
303/// in the call's trusted-issuer list, never on its own say-so.
304fn keys_for<'a>(key: &'a [u8], issuer_did: Option<&'a str>) -> Keys<'a> {
305    match issuer_did {
306        _ if key.is_empty() => Keys::Embedded,
307        Some(d) if !d.is_empty() => Keys::One(d, key),
308        _ => Keys::Bare(key),
309    }
310}
311
312/// The key source for a facade call that checks a SELF-ATTESTATION (the robot,
313/// agent or party describes itself). Like [`keys_for`], except that an empty
314/// key with a DID pins that DID: the caller says which party must have
315/// signed, so that party's did:key verifies under the key inside its DID.
316fn keys_self<'a>(key: &'a [u8], issuer_did: Option<&'a str>) -> Keys<'a> {
317    match issuer_did {
318        Some(d) if key.is_empty() && !d.is_empty() => Keys::Pinned(d),
319        _ => keys_for(key, issuer_did),
320    }
321}
322
323fn trusted_set(json: Option<&str>, name: &str) -> Result<Option<HashSet<String>>> {
324    match opt_obj(json)? {
325        None => Ok(None),
326        Some(Value::Array(a)) => Ok(Some(strs_of(&a, name)?.into_iter().collect())),
327        Some(_) => Err(wrong_type(name, "a list of strings")),
328    }
329}
330
331fn subj(opt: Option<Value>) -> String {
332    opt.unwrap_or(Value::Null).to_string()
333}
334
335// ---- identity -------------------------------------------------------------
336
337pub fn mint_robot_identity(robot_seed: &[u8], params_json: &str) -> Result<String> {
338    let p = parse(params_json)?;
339    let params = r::MintRobotIdentity {
340        robot_did: gs(&p, "robotDid")?,
341        make: gs(&p, "make")?,
342        model: gs(&p, "model")?,
343        serial: gs(&p, "serial")?,
344        owner: gos(&p, "owner")?,
345        root_kind: gs(&p, "rootKind")?,
346        root_public_multibase: gs(&p, "rootPublicMultibase")?,
347        attestation: r::unmb64(&gs(&p, "attestation")?)?,
348        lifecycle: p.get("lifecycle").filter(|v| !v.is_null()).cloned(),
349        valid_from: gs(&p, "validFrom")?,
350        valid_until: gos(&p, "validUntil")?,
351    };
352    Ok(r::mint_robot_identity(robot_seed, &params)?.to_string())
353}
354
355/// Verify a robot identity credential. `robot_pub` is trusted for
356/// `issuer_did` (or, without one, only for a did:key robot); `hardware_root_mb`,
357/// when given, pins the hardware-root key (multikey). Windows are checked at
358/// `now_iso`.
359pub fn verify_robot_identity(
360    credential_json: &str,
361    robot_pub: &[u8],
362    issuer_did: Option<&str>,
363    hardware_root_mb: Option<&str>,
364    now_iso: &str,
365) -> Result<String> {
366    let pin = match hardware_root_mb.filter(|m| !m.is_empty()) {
367        Some(m) => {
368            let decoded = crate::multikey::decode(m)?;
369            if decoded.algorithm != "Ed25519" {
370                return Err(CoreError::InvalidMultikey(
371                    "the hardware root key must be an Ed25519 Multikey".into(),
372                ));
373            }
374            Some(decoded.raw_key)
375        }
376        None => None,
377    };
378    Ok(subj(r::verify_robot_identity(
379        &parse(credential_json)?,
380        keys_self(robot_pub, issuer_did),
381        pin.as_deref(),
382        now_iso,
383    )?))
384}
385// ---- provenance -----------------------------------------------------------
386
387pub fn config_hash(config_json: &str) -> Result<String> {
388    Ok(r::config_hash(&parse(config_json)?))
389}
390
391pub fn build_provenance_attestation(signer_seed: &[u8], params_json: &str) -> Result<String> {
392    let p = parse(params_json)?;
393    let params = r::BuildProvenance {
394        issuer_did: gs(&p, "issuerDid")?,
395        robot_did: gs(&p, "robotDid")?,
396        model_name: gs(&p, "modelName")?,
397        weights_hash: gs(&p, "weightsHash")?,
398        safety_policy: gs(&p, "safetyPolicy")?,
399        config: p.get("config").filter(|v| !v.is_null()).cloned(),
400        version: gos(&p, "version")?,
401        supersedes: gos(&p, "supersedes")?,
402        valid_from: gs(&p, "validFrom")?,
403        valid_until: gos(&p, "validUntil")?,
404    };
405    Ok(r::build_provenance_attestation(signer_seed, &params)?.to_string())
406}
407
408pub fn verify_provenance_attestation(
409    attestation_json: &str,
410    public_key: &[u8],
411    config_json: Option<&str>,
412    issuer_did: Option<&str>,
413    now_iso: &str,
414) -> Result<String> {
415    let config = opt_obj(config_json)?;
416    Ok(subj(r::verify_provenance_attestation(
417        &parse(attestation_json)?,
418        keys_self(public_key, issuer_did),
419        config.as_ref(),
420        now_iso,
421    )?))
422}
423// ---- capability -----------------------------------------------------------
424
425pub fn build_physical_scope_credential(signer_seed: &[u8], params_json: &str) -> Result<String> {
426    let p = parse(params_json)?;
427    let params = r::BuildPhysicalScope {
428        issuer_did: gs(&p, "issuerDid")?,
429        subject_did: gs(&p, "subjectDid")?,
430        max_force_n: gof(&p, "maxForceN")?,
431        max_speed_mps: gof(&p, "maxSpeedMps")?,
432        max_speed_near_humans_mps: gof(&p, "maxSpeedNearHumansMps")?,
433        allowed_zones: gostrs(&p, "allowedZones")?,
434        shift_windows: gwindows(&p, "shiftWindows")?,
435        valid_from: gs(&p, "validFrom")?,
436        valid_until: gos(&p, "validUntil")?,
437    };
438    Ok(r::build_physical_scope_credential(signer_seed, &params)?.to_string())
439}
440
441/// Check an action against a SIGNED `PhysicalCapabilityScope` credential: the
442/// credential is verified first (bound to its issuer, `public_key` trusted for
443/// `issuer_did` or, without one, only for a did:key issuer; in its window at
444/// `now_iso`; well-formed scope with no unknown dimension; for `robot_did`
445/// when given). The action may carry only forceN / speedMps / nearHumans /
446/// zone / timeHm, with real types. Returns `{ok, reasons}`; a scope that does
447/// not verify gives `{ok: false, reasons: ["scope credential does not verify"]}`.
448pub fn check_physical_action(
449    scope_credential_json: &str,
450    action_json: &str,
451    public_key: &[u8],
452    issuer_did: Option<&str>,
453    robot_did: Option<&str>,
454    now_iso: &str,
455) -> Result<String> {
456    let action = action_from(&parse(action_json)?)?;
457    let scope = match r::verify_physical_scope_credential(
458        &parse(scope_credential_json)?,
459        keys_for(public_key, issuer_did),
460        robot_did.filter(|d| !d.is_empty()),
461        now_iso,
462    )? {
463        Some(sc) => sc,
464        None => {
465            return Ok(
466                json!({"ok": false, "reasons": ["scope credential does not verify"]}).to_string(),
467            )
468        }
469    };
470    let res = r::check_physical_action(&scope, &action);
471    Ok(json!({"ok": res.ok, "reasons": res.reasons}).to_string())
472}
473
474/// Check an action against an already-verified physicalScope object (no
475/// credential check). Prefer [`check_physical_action`] at a trust boundary.
476pub fn check_physical_action_scope(scope_json: &str, action_json: &str) -> Result<String> {
477    let action = action_from(&parse(action_json)?)?;
478    let res = r::check_physical_action(&parse(scope_json)?, &action);
479    Ok(json!({"ok": res.ok, "reasons": res.reasons}).to_string())
480}
481
482pub fn attenuates(parent_json: &str, child_json: &str) -> Result<bool> {
483    Ok(r::attenuates(&parse(parent_json)?, &parse(child_json)?))
484}
485
486// ---- handshake ------------------------------------------------------------
487
488fn policy(policy_json: Option<&str>) -> Result<Option<r::TrustPolicy>> {
489    match opt_obj(policy_json)? {
490        Some(v) => Ok(Some(r::TrustPolicy::new(
491            gstrs(&v, "trustedDomains")?,
492            gbool(&v, "acceptUnknown")?,
493        ))),
494        None => Ok(None),
495    }
496}
497
498fn session_to_json(s: &r::BoundedSession) -> Value {
499    json!({
500        "sessionId": s.session_id,
501        "initiator": s.initiator,
502        "responder": s.responder,
503        "scope": s.scope,
504        "nonce": s.nonce,
505        "validUntil": s.valid_until,
506    })
507}
508
509fn session_from_json(v: &Value) -> Result<r::BoundedSession> {
510    Ok(r::BoundedSession {
511        session_id: gs(v, "sessionId")?,
512        initiator: gs(v, "initiator")?,
513        responder: gs(v, "responder")?,
514        scope: gstrs(v, "scope")?,
515        nonce: gs(v, "nonce")?,
516        valid_until: gos(v, "validUntil")?,
517    })
518}
519
520pub fn build_hello(signer_seed: &[u8], params_json: &str) -> Result<String> {
521    let p = parse(params_json)?;
522    let params = r::BuildHello {
523        from_did: gs(&p, "fromDid")?,
524        proposed_scope: gstrs(&p, "proposedScope")?,
525        nonce: gs(&p, "nonce")?,
526        peer_did: gos(&p, "peerDid")?,
527        issued_at: gs(&p, "issuedAt")?,
528    };
529    Ok(r::build_hello(signer_seed, &params)?.to_string())
530}
531
532/// B: verify A's HELLO and sign an ACCEPT. `params_json` is `{fromDid,
533/// offeredScope, sessionId, validUntil, created, helloFromDid?}`;
534/// `hello_public_key` is trusted for `helloFromDid` (without it, only for a
535/// did:key initiator). `created` is the responder's clock.
536pub fn build_accept(
537    signer_seed: &[u8],
538    hello_json: &str,
539    hello_public_key: &[u8],
540    policy_json: &str,
541    params_json: &str,
542) -> Result<String> {
543    let pol = policy(Some(policy_json))?.unwrap_or_default();
544    let p = parse(params_json)?;
545    let params = r::BuildAccept {
546        from_did: gs(&p, "fromDid")?,
547        offered_scope: gstrs(&p, "offeredScope")?,
548        session_id: gs(&p, "sessionId")?,
549        valid_until: gs(&p, "validUntil")?,
550        created: gs(&p, "created")?,
551    };
552    let hello_did = gos(&p, "helloFromDid")?;
553    let limits = r::HandshakeLimits {
554        clock_skew_seconds: oint(&p, "clockSkewSeconds")?
555            .unwrap_or(r::DEFAULT_HANDSHAKE_SKEW_SECONDS),
556        max_age_seconds: oint(&p, "maxHelloAgeSeconds")?
557            .unwrap_or(r::DEFAULT_MAX_HELLO_AGE_SECONDS),
558        ..r::HandshakeLimits::default()
559    };
560    Ok(r::build_accept_with(
561        signer_seed,
562        &parse(hello_json)?,
563        keys_self(hello_public_key, hello_did.as_deref()),
564        &pol,
565        &params,
566        limits,
567    )?
568    .to_string())
569}
570
571/// A: verify B's ACCEPT against the HELLO A sent, at `now_iso`.
572/// `accept_public_key` is trusted for `responder_did` (without it, only for a
573/// did:key responder). Returns the session JSON or `null`.
574pub fn verify_accept(
575    accept_json: &str,
576    accept_public_key: &[u8],
577    hello_json: &str,
578    expected_nonce: Option<&str>,
579    policy_json: Option<&str>,
580    responder_did: Option<&str>,
581    now_iso: &str,
582) -> Result<String> {
583    let pol = policy(policy_json)?;
584    let session = r::verify_accept(
585        &parse(accept_json)?,
586        keys_self(accept_public_key, responder_did),
587        &parse(hello_json)?,
588        expected_nonce.filter(|n| !n.is_empty()),
589        pol.as_ref(),
590        now_iso,
591    )?;
592    Ok(session
593        .map(|s| session_to_json(&s))
594        .unwrap_or(Value::Null)
595        .to_string())
596}
597
598pub fn build_confirm(
599    signer_seed: &[u8],
600    from_did: &str,
601    session_json: &str,
602    created: &str,
603) -> Result<String> {
604    let session = session_from_json(&parse(session_json)?)?;
605    Ok(r::build_confirm(signer_seed, from_did, &session, created)?.to_string())
606}
607
608/// B: verify A's CONFIRM against the ACCEPT B sent, at `now_iso`.
609/// `confirm_public_key` is trusted for `initiator_did` (without it, only for a
610/// did:key initiator).
611pub fn verify_confirm(
612    confirm_json: &str,
613    confirm_public_key: &[u8],
614    accept_json: &str,
615    initiator_did: Option<&str>,
616    now_iso: &str,
617) -> Result<bool> {
618    r::verify_confirm(
619        &parse(confirm_json)?,
620        keys_self(confirm_public_key, initiator_did),
621        &parse(accept_json)?,
622        now_iso,
623    )
624}
625
626// ---- black box and kill switch -------------------------------------------
627
628pub fn genesis_prev_hash() -> String {
629    r::genesis_prev_hash()
630}
631
632pub fn blackbox_append_entry(
633    key: &[u8],
634    seq: u64,
635    event: &str,
636    payload_json: &str,
637    timestamp: &str,
638    prev_hash: &str,
639) -> Result<String> {
640    Ok(
641        r::blackbox_append_entry(key, seq, event, &parse(payload_json)?, timestamp, prev_hash)?
642            .to_string(),
643    )
644}
645
646pub fn blackbox_open_entry(entry_json: &str, key: &[u8]) -> Result<String> {
647    Ok(r::open_entry(&parse(entry_json)?, key)?.to_string())
648}
649
650pub fn verify_blackbox_chain(
651    entries_json: &str,
652    genesis_prev_hash: Option<&str>,
653) -> Result<String> {
654    verify_blackbox_chain_with(entries_json, genesis_prev_hash, LogLimits::DEFAULT)
655}
656
657pub(crate) fn verify_blackbox_chain_with(
658    entries_json: &str,
659    genesis_prev_hash: Option<&str>,
660    limits: LogLimits,
661) -> Result<String> {
662    let entries = parse_long_with(entries_json, limits)?;
663    let arr = entries
664        .as_array()
665        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
666    let res = r::verify_blackbox_chain_capped(arr, genesis_prev_hash, limits.max_bytes);
667    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
668}
669
670pub fn build_killswitch_credential(authority_seed: &[u8], params_json: &str) -> Result<String> {
671    let p = parse(params_json)?;
672    let params = r::BuildKillswitch {
673        issuer_did: gs(&p, "issuerDid")?,
674        target: gs(&p, "target")?,
675        reason: gs(&p, "reason")?,
676        command: gos(&p, "command")?,
677        scope: gostrs(&p, "scope")?,
678        valid_from: gs(&p, "validFrom")?,
679        valid_until: gos(&p, "validUntil")?,
680    };
681    Ok(r::build_killswitch_credential(authority_seed, &params)?.to_string())
682}
683
684pub fn verify_killswitch_credential(
685    credential_json: &str,
686    public_key: &[u8],
687    trusted_authorities_json: Option<&str>,
688    issuer_did: Option<&str>,
689    now_iso: &str,
690) -> Result<String> {
691    let trusted = trusted_set(trusted_authorities_json, "trustedAuthorities")?;
692    Ok(subj(r::verify_killswitch_credential(
693        &parse(credential_json)?,
694        keys_for(public_key, issuer_did),
695        trusted.as_ref(),
696        now_iso,
697    )?))
698}
699
700/// Check a black-box log against a signed head. `params_json` is `{head:
701/// {...}, entries: [...], genesisPrevHash?}`; `robot_pub` is trusted for
702/// `issuer_did`. Returns `{ok, reason}`.
703pub fn verify_blackbox_head(
704    params_json: &str,
705    robot_pub: &[u8],
706    issuer_did: Option<&str>,
707    now_iso: &str,
708) -> Result<String> {
709    verify_blackbox_head_with(
710        params_json,
711        robot_pub,
712        issuer_did,
713        now_iso,
714        LogLimits::DEFAULT,
715    )
716}
717
718pub(crate) fn verify_blackbox_head_with(
719    params_json: &str,
720    robot_pub: &[u8],
721    issuer_did: Option<&str>,
722    now_iso: &str,
723    limits: LogLimits,
724) -> Result<String> {
725    let p = parse_long_with(params_json, limits)?;
726    let head = p.get("head").cloned().unwrap_or(Value::Null);
727    let entries = garr(&p, "entries")?;
728    let genesis = gos(&p, "genesisPrevHash")?;
729    let mut progress = r::ChainProgress::start(genesis.as_deref());
730    r::verify_chain_segment(&mut progress, &entries, limits.max_bytes);
731    let res = r::finish_chain_against_head_credential(
732        &head,
733        keys_self(robot_pub, issuer_did),
734        &progress,
735        now_iso,
736    )?;
737    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
738}
739
740/// Sign a black-box head. `params_json` is `{robotDid, logHead, entryCount,
741/// validFrom, validUntil?}`.
742pub fn build_blackbox_head(robot_seed: &[u8], params_json: &str) -> Result<String> {
743    let p = parse(params_json)?;
744    let count = match p.get("entryCount") {
745        Some(v) if v.is_u64() => v.as_u64().unwrap_or(0),
746        _ => return Err(wrong_type("entryCount", "a non-negative whole number")),
747    };
748    Ok(r::build_blackbox_head(
749        robot_seed,
750        &gs(&p, "robotDid")?,
751        &gs(&p, "logHead")?,
752        count,
753        &gs(&p, "validFrom")?,
754        gos(&p, "validUntil")?.as_deref(),
755    )?
756    .to_string())
757}
758// ---- halos safety evidence ------------------------------------------------
759
760/// Seal a robot's Halos safety-event record into a signed
761/// `HalosSafetyEvidenceCredential`. `params_json` carries `{halosStack, window:
762/// {from, to}, blackboxHead, entryCount, robotIdentity?, validSeconds?, validFrom,
763/// created}`. The robot DID is derived from `signer_seed`.
764pub fn build_safety_evidence(signer_seed: &[u8], params_json: &str) -> Result<String> {
765    let p = parse(params_json)?;
766    let window = p.get("window").cloned().unwrap_or(Value::Null);
767    let params = r::BuildSafetyEvidence {
768        halos_stack: p.get("halosStack").cloned().unwrap_or(Value::Null),
769        window_from: gs(&window, "from")?,
770        window_to: gs(&window, "to")?,
771        blackbox_head: gs(&p, "blackboxHead")?,
772        entry_count: match present(&p, "entryCount") {
773            None => 0,
774            Some(v) => v
775                .as_u64()
776                .ok_or_else(|| wrong_type("entryCount", "a whole number"))?,
777        },
778        robot_identity: gos(&p, "robotIdentity")?,
779        valid_seconds: match present(&p, "validSeconds") {
780            None => None,
781            Some(v) => Some(
782                v.as_i64()
783                    .ok_or_else(|| wrong_type("validSeconds", "a whole number"))?,
784            ),
785        },
786        valid_from: gs(&p, "validFrom")?,
787        created: gs(&p, "created")?,
788        robot_did: gos(&p, "robotDid")?,
789    };
790    Ok(r::build_safety_evidence(signer_seed, &params)?.to_string())
791}
792
793/// Verify a Halos safety-evidence credential. `entries_json` is the black-box
794/// entries as a JSON array, or `""`/`"null"` for none. Returns `{ok, subject}`
795/// where `subject` is the credentialSubject or the JSON literal `null`.
796pub fn verify_safety_evidence(
797    credential_json: &str,
798    robot_pub: &[u8],
799    entries_json: &str,
800    issuer_did: Option<&str>,
801    now_iso: &str,
802) -> Result<String> {
803    let credential = parse(credential_json)?;
804    let entries = opt_obj(Some(entries_json))?;
805    let entries_slice = match &entries {
806        Some(v) => Some(
807            v.as_array()
808                .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?
809                .as_slice(),
810        ),
811        None => None,
812    };
813    let (ok, subject) = r::verify_safety_evidence(
814        &credential,
815        keys_self(robot_pub, issuer_did),
816        entries_slice,
817        now_iso,
818    )?;
819    Ok(json!({"ok": ok, "subject": subject.unwrap_or(Value::Null)}).to_string())
820}
821// ---- passport -------------------------------------------------------------
822
823pub fn build_passport(signer_seed: &[u8], params_json: &str) -> Result<String> {
824    let p = parse(params_json)?;
825    let params = r::BuildPassport {
826        issuer_did: gs(&p, "issuerDid")?,
827        robot_did: gs(&p, "robotDid")?,
828        make: gs(&p, "make")?,
829        model: gs(&p, "model")?,
830        owner: gs(&p, "owner")?,
831        authorized_actions: gstrs(&p, "authorizedActions")?,
832        certification: gos(&p, "certification")?,
833        status: gos(&p, "status")?,
834        valid_from: gs(&p, "validFrom")?,
835        valid_until: gos(&p, "validUntil")?,
836    };
837    Ok(r::build_passport(signer_seed, &params)?.to_string())
838}
839
840pub fn encode_passport(passport_json: &str) -> Result<String> {
841    Ok(r::encode_passport(&parse(passport_json)?))
842}
843
844pub fn decode_passport(uri: &str) -> Result<String> {
845    Ok(r::decode_passport(uri)?.to_string())
846}
847
848pub fn verify_passport(
849    passport_json: &str,
850    public_key: &[u8],
851    now_iso: &str,
852    issuer_did: Option<&str>,
853) -> Result<String> {
854    Ok(subj(r::verify_passport(
855        &parse(passport_json)?,
856        keys_for(public_key, issuer_did),
857        None,
858        now_iso,
859    )?))
860}
861pub fn verify_passport_uri(
862    uri: &str,
863    public_key: &[u8],
864    now_iso: &str,
865    issuer_did: Option<&str>,
866) -> Result<String> {
867    Ok(subj(r::verify_passport_uri(
868        uri,
869        keys_for(public_key, issuer_did),
870        None,
871        now_iso,
872    )?))
873}
874// ---- liveness -------------------------------------------------------------
875
876fn gi(v: &Value, k: &str) -> Result<i64> {
877    match present(v, k) {
878        None => Ok(0),
879        Some(x) => x.as_i64().ok_or_else(|| wrong_type(k, "a whole number")),
880    }
881}
882
883/// Build a motionDigest from a JSON array of samples against an optional scope.
884/// `params_json` is `{"scope": {...}|null, "samples": [{forceN, speedMps,
885/// nearHumans, zone, timeHm}, ...]}`.
886pub fn motion_digest(params_json: &str) -> Result<String> {
887    let p = parse(params_json)?;
888    let scope = p.get("scope").filter(|v| !v.is_null()).cloned();
889    let mut collector = r::MotionCollector::new(scope);
890    for s in garr(&p, "samples")? {
891        if !s.is_object() {
892            return Err(wrong_type("samples", "a list of objects"));
893        }
894        collector.record(&r::MotionSample {
895            force_n: gof(&s, "forceN")?,
896            speed_mps: gof(&s, "speedMps")?,
897            near_humans: gbool(&s, "nearHumans")?,
898            zone: gos(&s, "zone")?,
899            time_hm: gos(&s, "timeHm")?,
900        })?;
901    }
902    Ok(collector.digest().to_string())
903}
904
905pub fn validate_motion_digest(digest_json: &str) -> Result<bool> {
906    Ok(r::validate_motion_digest(&parse(digest_json)?).is_ok())
907}
908
909pub fn build_robot_heartbeat(robot_seed: &[u8], params_json: &str) -> Result<String> {
910    let p = parse(params_json)?;
911    let params = r::BuildRobotHeartbeat {
912        robot_did: gs(&p, "robotDid")?,
913        session_id: gs(&p, "sessionId")?,
914        interval_index: gi(&p, "intervalIndex")?,
915        interval_seconds: gi(&p, "intervalSeconds")?,
916        motion_digest: p.get("motionDigest").cloned().unwrap_or(Value::Null),
917        valid_from: gs(&p, "validFrom")?,
918    };
919    Ok(r::build_robot_heartbeat(robot_seed, &params)?.to_string())
920}
921
922pub fn verify_robot_heartbeat(
923    credential_json: &str,
924    robot_public_key: &[u8],
925    issuer_did: Option<&str>,
926    now_iso: &str,
927) -> Result<String> {
928    Ok(subj(r::verify_robot_heartbeat(
929        &parse(credential_json)?,
930        keys_self(robot_public_key, issuer_did),
931        now_iso,
932    )?))
933}
934pub fn is_live(
935    credential_json: &str,
936    now_iso: &str,
937    interval_seconds: Option<i64>,
938    grace_intervals: i64,
939) -> Result<bool> {
940    r::is_live(
941        &parse(credential_json)?,
942        now_iso,
943        interval_seconds,
944        grace_intervals,
945    )
946}
947
948// ---- revocation -----------------------------------------------------------
949
950pub fn build_status_list_entry(
951    status_list_credential: &str,
952    status_list_index: i64,
953    status_purpose: &str,
954    entry_id: Option<&str>,
955) -> Result<String> {
956    Ok(r::build_status_list_entry(
957        status_list_credential,
958        status_list_index,
959        status_purpose,
960        entry_id,
961    )?
962    .to_string())
963}
964
965pub fn attach_credential_status(
966    credential_json: &str,
967    signer_seed: &[u8],
968    params_json: &str,
969) -> Result<String> {
970    let p = parse(params_json)?;
971    let params = r::AttachCredentialStatus {
972        status_list_credential: gs(&p, "statusListCredential")?,
973        status_list_index: gi(&p, "statusListIndex")?,
974        status_purpose: gos(&p, "statusPurpose")?
975            .unwrap_or_else(|| r::STATUS_PURPOSE_REVOCATION.to_string()),
976        entry_id: gos(&p, "entryId")?,
977        created: gs(&p, "created")?,
978    };
979    Ok(r::attach_credential_status(&parse(credential_json)?, signer_seed, &params)?.to_string())
980}
981
982pub fn check_credential_status(
983    credential_json: &str,
984    status_list_credential_json: &str,
985    status_purpose: &str,
986) -> Result<bool> {
987    r::check_credential_status(
988        &parse(credential_json)?,
989        &parse(status_list_credential_json)?,
990        status_purpose,
991    )
992}
993
994// ---- safety record --------------------------------------------------------
995
996/// Append one event to a ledger and return `{entry, head}`. The chain is
997/// stateless across calls: pass the previous head as `prevHash` (or the genesis).
998/// `params_json` is `{eventType, severity, details?, actor?, timestamp,
999/// prevHash, seq}`.
1000pub fn safety_append_entry(params_json: &str) -> Result<String> {
1001    let p = parse(params_json)?;
1002    let prev = gs(&p, "prevHash")?;
1003    let mut log = r::SafetyEventLog::resume(&prev, gseq(&p)?);
1004    let entry = log.append(
1005        &gs(&p, "eventType")?,
1006        &gs(&p, "severity")?,
1007        p.get("details").filter(|v| !v.is_null()),
1008        gos(&p, "actor")?.as_deref(),
1009        &gs(&p, "timestamp")?,
1010    )?;
1011    Ok(json!({"entry": entry, "head": log.head()}).to_string())
1012}
1013
1014pub fn verify_safety_log(entries_json: &str, genesis_prev_hash: Option<&str>) -> Result<String> {
1015    verify_safety_log_with(entries_json, genesis_prev_hash, LogLimits::DEFAULT)
1016}
1017
1018pub(crate) fn verify_safety_log_with(
1019    entries_json: &str,
1020    genesis_prev_hash: Option<&str>,
1021    limits: LogLimits,
1022) -> Result<String> {
1023    verify_blackbox_chain_with(entries_json, genesis_prev_hash, limits)
1024}
1025
1026pub fn summarize_entries(entries_json: &str, head: Option<&str>) -> Result<String> {
1027    let entries = parse(entries_json)?;
1028    let arr = entries
1029        .as_array()
1030        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
1031    Ok(r::summarize_entries(arr, head).to_string())
1032}
1033
1034pub fn build_safety_record(signer_seed: &[u8], params_json: &str) -> Result<String> {
1035    let p = parse(params_json)?;
1036    let params = r::BuildSafetyRecord {
1037        issuer_did: gs(&p, "issuerDid")?,
1038        robot_did: gs(&p, "robotDid")?,
1039        summary: p.get("summary").cloned().unwrap_or(Value::Null),
1040        period_start: gos(&p, "periodStart")?,
1041        period_end: gos(&p, "periodEnd")?,
1042        valid_from: gs(&p, "validFrom")?,
1043        valid_until: gos(&p, "validUntil")?,
1044    };
1045    Ok(r::build_safety_record(signer_seed, &params)?.to_string())
1046}
1047
1048/// Verify a safety record. `entries_json`, when not empty or `null`, is the
1049/// ledger (a JSON array) checked against the record's head and counts.
1050pub fn verify_safety_record(
1051    credential_json: &str,
1052    public_key: &[u8],
1053    entries_json: Option<&str>,
1054    issuer_did: Option<&str>,
1055    now_iso: &str,
1056) -> Result<String> {
1057    let entries = opt_obj(entries_json)?;
1058    let slice = match &entries {
1059        Some(Value::Array(a)) => Some(a.as_slice()),
1060        Some(_) => return Err(wrong_type("entries", "a list")),
1061        None => None,
1062    };
1063    Ok(subj(r::verify_safety_record(
1064        &parse(credential_json)?,
1065        keys_for(public_key, issuer_did),
1066        r::SafetyRecordCheck {
1067            entries: slice,
1068            robot_did: None,
1069            trusted_issuers: None,
1070        },
1071        now_iso,
1072    )?))
1073}
1074// ---- perception provenance ------------------------------------------------
1075
1076/// Multibase SHA-256 of a raw sensor frame.
1077pub fn hash_frame(frame: &[u8]) -> String {
1078    r::hash_frame(frame)
1079}
1080
1081/// Append one frame-provenance record to a log and return `{entry, head}`. The
1082/// chain is stateless across calls: pass the previous head as `prevHash` (or the
1083/// genesis). `params_json` is `{sensorId, modality, frameHash|frame_mb,
1084/// timestamp, prevHash}` where `frame_mb` is a multibase-encoded raw frame.
1085pub fn perception_record_entry(params_json: &str) -> Result<String> {
1086    let p = parse(params_json)?;
1087    let prev = gs(&p, "prevHash")?;
1088    let mut log = r::PerceptionLog::resume(&prev, gseq(&p)?);
1089    let frame = match gos(&p, "frameMb")? {
1090        Some(mb) => Some(r::unmb64(&mb)?),
1091        None => None,
1092    };
1093    let entry = log.record(
1094        &gs(&p, "sensorId")?,
1095        &gs(&p, "modality")?,
1096        frame.as_deref(),
1097        gos(&p, "frameHash")?.as_deref(),
1098        &gs(&p, "timestamp")?,
1099    )?;
1100    Ok(json!({"entry": entry, "head": log.head()}).to_string())
1101}
1102
1103pub fn verify_perception_log(
1104    entries_json: &str,
1105    genesis_prev_hash: Option<&str>,
1106) -> Result<String> {
1107    verify_perception_log_with(entries_json, genesis_prev_hash, LogLimits::DEFAULT)
1108}
1109
1110pub(crate) fn verify_perception_log_with(
1111    entries_json: &str,
1112    genesis_prev_hash: Option<&str>,
1113    limits: LogLimits,
1114) -> Result<String> {
1115    verify_blackbox_chain_with(entries_json, genesis_prev_hash, limits)
1116}
1117
1118pub fn build_perception_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
1119    let p = parse(params_json)?;
1120    let params = r::BuildPerception {
1121        robot_did: gs(&p, "robotDid")?,
1122        sensor_id: gs(&p, "sensorId")?,
1123        modality: gs(&p, "modality")?,
1124        frame_hash: gs(&p, "frameHash")?,
1125        captured_at: gos(&p, "capturedAt")?,
1126        log_head: gos(&p, "logHead")?,
1127        log_count: match p.get("logCount") {
1128            None | Some(Value::Null) => None,
1129            Some(v) if v.is_u64() => v.as_u64(),
1130            Some(_) => return Err(wrong_type("logCount", "a non-negative whole number")),
1131        },
1132        valid_from: gs(&p, "validFrom")?,
1133        valid_until: gos(&p, "validUntil")?,
1134    };
1135    Ok(r::build_perception_attestation(robot_seed, &params)?.to_string())
1136}
1137
1138/// Verify a perception attestation. When `frame_mb` is a non-empty multibase
1139/// string, the raw frame is decoded and its hash compared to the attested value.
1140pub fn verify_perception_attestation(
1141    credential_json: &str,
1142    public_key: &[u8],
1143    frame_mb: Option<&str>,
1144    issuer_did: Option<&str>,
1145    now_iso: &str,
1146) -> Result<String> {
1147    let frame = match frame_mb {
1148        Some(mb) if !mb.is_empty() => Some(r::unmb64(mb)?),
1149        _ => None,
1150    };
1151    Ok(subj(r::verify_perception_attestation(
1152        &parse(credential_json)?,
1153        keys_self(public_key, issuer_did),
1154        frame.as_deref(),
1155        now_iso,
1156    )?))
1157}
1158
1159/// Verify a perception log segment against a signed attestation. `params_json`
1160/// is `{entries: [...], attestation: {...}, genesisPrevHash?}`. Returns `{ok,
1161/// reason}`.
1162pub fn verify_perception_segment(
1163    params_json: &str,
1164    public_key: &[u8],
1165    issuer_did: Option<&str>,
1166    now_iso: &str,
1167) -> Result<String> {
1168    let p = parse(params_json)?;
1169    let entries = garr(&p, "entries")?;
1170    let att = p.get("attestation").cloned().unwrap_or(Value::Null);
1171    let genesis = gos(&p, "genesisPrevHash")?;
1172    let res = r::verify_perception_segment(
1173        &entries,
1174        &att,
1175        keys_self(public_key, issuer_did),
1176        genesis.as_deref(),
1177        now_iso,
1178    )?;
1179    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
1180}
1181// ---- delegation lease -----------------------------------------------------
1182
1183pub fn build_delegation_lease(signer_seed: &[u8], params_json: &str) -> Result<String> {
1184    let p = parse(params_json)?;
1185    let params = r::BuildDelegationLease {
1186        issuer_did: gs(&p, "issuerDid")?,
1187        robot_did: gs(&p, "robotDid")?,
1188        lease_id: gs(&p, "leaseId")?,
1189        scope: p.get("scope").cloned().unwrap_or(Value::Null),
1190        parent_lease_id: gos(&p, "parentLeaseId")?,
1191        valid_from: gs(&p, "validFrom")?,
1192        valid_until: gs(&p, "validUntil")?,
1193    };
1194    Ok(r::build_delegation_lease(signer_seed, &params)?.to_string())
1195}
1196
1197/// Verify a delegation lease at `now_iso`, the verifier's clock (the wrappers
1198/// pass the host clock when their caller gives none; an empty or malformed
1199/// clock is an error). The lease must be for `expected_robot`; the key is
1200/// trusted for `issuer_did` (without one, only for a did:key issuer).
1201pub fn verify_delegation_lease(
1202    credential_json: &str,
1203    public_key: &[u8],
1204    now_iso: &str,
1205    parent_scope_json: Option<&str>,
1206    issuer_did: Option<&str>,
1207    expected_robot: &str,
1208) -> Result<String> {
1209    let parent = opt_obj(parent_scope_json)?;
1210    Ok(subj(r::verify_delegation_lease(
1211        &parse(credential_json)?,
1212        keys_for(public_key, issuer_did),
1213        expected_robot,
1214        parent.as_ref(),
1215        None,
1216        now_iso,
1217    )?))
1218}
1219
1220/// Verify a lease chain. `params_json` is `{leases: [...], publicKeys: {did:
1221/// keyB64url}, expectedRobot, rootIssuers: [...], now?}`. Returns `{ok, leaf}`.
1222pub fn verify_lease_chain(params_json: &str, host_now: &str) -> Result<String> {
1223    let p = parse(params_json)?;
1224    let leases = garr(&p, "leases")?;
1225    let keys = owner_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
1226    let map = Keys::map_of(keys.into_iter().map(|k| (k.did, k.public_key)));
1227    let roots: HashSet<String> = gstrs(&p, "rootIssuers")?.into_iter().collect();
1228    let now = now_or(&p, host_now)?;
1229    let leaf = r::verify_lease_chain(
1230        &leases,
1231        Keys::Map(&map),
1232        &gs(&p, "expectedRobot")?,
1233        &roots,
1234        &now,
1235    )?;
1236    Ok(json!({"ok": leaf.is_some(), "leaf": leaf}).to_string())
1237}
1238
1239/// Decide whether a verified lease subject permits a proposed action.
1240/// `params_json` is `{subject, action, credential?, now?}` where `action` is the
1241/// same shape as [`check_physical_action`]'s action object. Without `now`, the
1242/// window is checked against `host_now`, the host clock the wrapper supplies.
1243/// Decide whether a lease permits an action. `params_json` is `{subject,
1244/// action, credential, publicKeys?: {did: keyB64url}, trustedIssuers?: [...],
1245/// now?}`. The lease credential is verified again under `publicKeys` (or, with
1246/// none, a did:key issuer named in `trustedIssuers`), so a re-dated copy fails.
1247pub fn lease_permits(params_json: &str, host_now: &str) -> Result<bool> {
1248    let p = parse(params_json)?;
1249    let subject = p.get("subject").cloned().unwrap_or(Value::Null);
1250    let action = action_from(p.get("action").unwrap_or(&Value::Null))?;
1251    let credential = p.get("credential").filter(|v| !v.is_null()).cloned();
1252    let now = now_or(&p, host_now)?;
1253    let keys = KeyIn::from(&p, "publicKeys")?;
1254    let trusted = trusted_of(&p)?;
1255    r::lease_permits(
1256        &subject,
1257        &action,
1258        credential.as_ref(),
1259        keys.keys(),
1260        trusted.as_ref(),
1261        &now,
1262    )
1263}
1264
1265// ---- physical quorum ------------------------------------------------------
1266
1267pub fn build_action_approval(approver_seed: &[u8], params_json: &str) -> Result<String> {
1268    let p = parse(params_json)?;
1269    let params = r::BuildActionApproval {
1270        approver_did: gs(&p, "approverDid")?,
1271        action_id: gs(&p, "actionId")?,
1272        robot_did: gs(&p, "robotDid")?,
1273        decision: gos(&p, "decision")?.unwrap_or_else(|| r::APPROVE.to_string()),
1274        valid_from: gs(&p, "validFrom")?,
1275        valid_until: gos(&p, "validUntil")?,
1276    };
1277    Ok(r::build_action_approval(approver_seed, &params)?.to_string())
1278}
1279
1280/// Verify a quorum authorization. `params_json` is `{approvals: [...], actionId,
1281/// robotDid, approverKeys: {did: keyB64url, ...}, threshold, approverSet?: [...],
1282/// now?}`. Each `approverKeys` value is the approver's Ed25519 public key as a
1283/// base64url-no-pad string (the same encoding as a JWK `x`). Without `now`, the
1284/// approval windows are checked against `host_now`, the host clock the wrapper
1285/// supplies. A present field of the wrong type (a non-list `approvals` or
1286/// `approverSet`, a non-integer `threshold`) is an error. Returns
1287/// `{authorized, approvers: [...]}`.
1288pub fn verify_action_authorization(params_json: &str, host_now: &str) -> Result<String> {
1289    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1290    use base64::Engine;
1291
1292    let p = parse(params_json)?;
1293    let approvals: Vec<Value> = garr(&p, "approvals")?;
1294    let action_id = gs(&p, "actionId")?;
1295    let robot_did = gs(&p, "robotDid")?;
1296    let threshold = gi(&p, "threshold")?;
1297
1298    let mut keys: Vec<r::ApproverKey> = Vec::new();
1299    let key_map = match present(&p, "approverKeys") {
1300        None => None,
1301        Some(Value::Object(o)) => Some(o),
1302        Some(_) => return Err(wrong_type("approverKeys", "an object")),
1303    };
1304    if let Some(obj) = key_map {
1305        for (did, key) in obj {
1306            let b64 = key
1307                .as_str()
1308                .ok_or_else(|| CoreError::Json("approverKeys values must be base64url".into()))?;
1309            let public_key = URL_SAFE_NO_PAD
1310                .decode(b64)
1311                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
1312            keys.push(r::ApproverKey {
1313                did: did.clone(),
1314                public_key,
1315            });
1316        }
1317    }
1318
1319    let approver_set: Option<HashSet<String>> =
1320        gostrs(&p, "approverSet")?.map(|v| v.into_iter().collect());
1321    let now = now_or(&p, host_now)?;
1322
1323    let (authorized, approvers) = r::verify_action_authorization_with(
1324        &approvals,
1325        &action_id,
1326        &robot_did,
1327        &keys,
1328        threshold,
1329        approver_set.as_ref(),
1330        oint(&p, "maxApprovalSeconds")?.unwrap_or(r::MAX_APPROVAL_SECONDS),
1331        &now,
1332    )?;
1333    Ok(json!({"authorized": authorized, "approvers": approvers}).to_string())
1334}
1335
1336// ---- robot lifecycle ------------------------------------------------------
1337
1338fn owner_keys(v: &Value) -> Result<Vec<r::OwnerKey>> {
1339    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1340    use base64::Engine;
1341    let mut keys: Vec<r::OwnerKey> = Vec::new();
1342    if !v.is_null() && !v.is_object() {
1343        return Err(wrong_type("publicKeys", "an object"));
1344    }
1345    if let Some(obj) = v.as_object() {
1346        for (did, key) in obj {
1347            let b64 = key
1348                .as_str()
1349                .ok_or_else(|| CoreError::Json("publicKeys values must be base64url".into()))?;
1350            let public_key = URL_SAFE_NO_PAD
1351                .decode(b64)
1352                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
1353            keys.push(r::OwnerKey {
1354                did: did.clone(),
1355                public_key,
1356            });
1357        }
1358    }
1359    Ok(keys)
1360}
1361
1362pub fn build_ownership_transfer(current_owner_seed: &[u8], params_json: &str) -> Result<String> {
1363    let p = parse(params_json)?;
1364    let params = r::BuildOwnershipTransfer {
1365        issuer_did: gs(&p, "issuerDid")?,
1366        robot_did: gs(&p, "robotDid")?,
1367        to_owner: gs(&p, "toOwner")?,
1368        from_owner: gos(&p, "fromOwner")?,
1369        prev_transfer_id: gos(&p, "prevTransferId")?,
1370        credential_id: gs(&p, "credentialId")?,
1371        valid_from: gs(&p, "validFrom")?,
1372    };
1373    Ok(r::build_ownership_transfer(current_owner_seed, &params)?.to_string())
1374}
1375
1376pub fn verify_ownership_transfer(
1377    credential_json: &str,
1378    public_key: &[u8],
1379    issuer_did: Option<&str>,
1380    robot_did: Option<&str>,
1381    now_iso: &str,
1382) -> Result<String> {
1383    Ok(subj(r::verify_ownership_transfer(
1384        &parse(credential_json)?,
1385        keys_self(public_key, issuer_did),
1386        robot_did.filter(|r| !r.is_empty()),
1387        now_iso,
1388    )?))
1389}
1390/// Verify a chain of custody. `params_json` is `{transfers: [...], publicKeys:
1391/// {did: keyB64url, ...}, robotDid, originOwner?, now?}` where each `publicKeys`
1392/// value is the owner's Ed25519 public key as a base64url-no-pad string.
1393/// Returns `{ok, currentOwner}`.
1394pub fn verify_custody_chain(params_json: &str, host_now: &str) -> Result<String> {
1395    let p = parse(params_json)?;
1396    let transfers: Vec<Value> = garr(&p, "transfers")?;
1397    let keys = owner_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
1398    let origin = gos(&p, "originOwner")?;
1399    let robot = gs(&p, "robotDid")?;
1400    let now = now_or(&p, host_now)?;
1401    let (ok, current) =
1402        r::verify_custody_chain(&transfers, &keys, &robot, origin.as_deref(), &now)?;
1403    Ok(json!({"ok": ok, "currentOwner": current}).to_string())
1404}
1405pub fn build_key_rotation(old_key_seed: &[u8], params_json: &str) -> Result<String> {
1406    let p = parse(params_json)?;
1407    let params = r::BuildKeyRotation {
1408        robot_did: gs(&p, "robotDid")?,
1409        new_key_multibase: gs(&p, "newKey")?,
1410        reason: gos(&p, "reason")?,
1411        valid_from: gs(&p, "validFrom")?,
1412    };
1413    Ok(r::build_key_rotation(old_key_seed, &params)?.to_string())
1414}
1415
1416/// Verify a key rotation. `old_public_key` is the key the caller trusts as the
1417/// robot's current key (bare); `robot_did`, when given, pins the robot.
1418pub fn verify_key_rotation(
1419    credential_json: &str,
1420    old_public_key: &[u8],
1421    robot_did: Option<&str>,
1422    now_iso: &str,
1423) -> Result<String> {
1424    Ok(subj(r::verify_key_rotation(
1425        &parse(credential_json)?,
1426        Keys::Bare(old_public_key),
1427        robot_did.filter(|r| !r.is_empty()),
1428        now_iso,
1429    )?))
1430}
1431/// Verify a key history. `params_json` is `{rotations: [...], originKey,
1432/// robotDid?, now?}`. Each rotation's key comes from its own multibase, so no
1433/// key map is taken. Returns `{ok, currentKey}`.
1434pub fn verify_key_history(params_json: &str, host_now: &str) -> Result<String> {
1435    let p = parse(params_json)?;
1436    let rotations: Vec<Value> = garr(&p, "rotations")?;
1437    let origin_key = gs(&p, "originKey")?;
1438    let robot = gos(&p, "robotDid")?;
1439    let now = now_or(&p, host_now)?;
1440    let (ok, current) = r::verify_key_history(&rotations, &origin_key, robot.as_deref(), &now)?;
1441    Ok(json!({"ok": ok, "currentKey": current}).to_string())
1442}
1443pub fn build_decommission(signer_seed: &[u8], params_json: &str) -> Result<String> {
1444    let p = parse(params_json)?;
1445    let params = r::BuildDecommission {
1446        issuer_did: gs(&p, "issuerDid")?,
1447        robot_did: gs(&p, "robotDid")?,
1448        reason: gs(&p, "reason")?,
1449        final_disposition: gos(&p, "finalDisposition")?,
1450        valid_from: gs(&p, "validFrom")?,
1451        valid_until: gos(&p, "validUntil")?,
1452    };
1453    Ok(r::build_decommission(signer_seed, &params)?.to_string())
1454}
1455
1456pub fn verify_decommission(
1457    credential_json: &str,
1458    public_key: &[u8],
1459    trusted_authorities_json: Option<&str>,
1460    issuer_did: Option<&str>,
1461    now_iso: &str,
1462) -> Result<String> {
1463    let trusted = trusted_set(trusted_authorities_json, "trustedAuthorities")?;
1464    Ok(subj(r::verify_decommission(
1465        &parse(credential_json)?,
1466        keys_for(public_key, issuer_did),
1467        trusted.as_ref(),
1468        None,
1469        now_iso,
1470    )?))
1471}
1472// ---- regulatory conformance -----------------------------------------------
1473
1474/// Check a credential set against a named profile and return the report.
1475/// `credentials_json` is a JSON array of credentials, or an object
1476/// `{credentials: [...], robotDid}` that binds the report to one robot (only
1477/// credentials about that robot count, and the report carries `robotDid`).
1478pub fn check_conformance(credentials_json: &str, profile_id: &str) -> Result<String> {
1479    let input = parse(credentials_json)?;
1480    let (credentials, robot) = match &input {
1481        Value::Array(a) => (a.clone(), None),
1482        Value::Object(_) => (garr(&input, "credentials")?, gos(&input, "robotDid")?),
1483        _ => {
1484            return Err(CoreError::Json(
1485                "credentials must be a JSON array or {credentials, robotDid}".into(),
1486            ))
1487        }
1488    };
1489    Ok(r::check_conformance_for(&credentials, profile_id, robot.as_deref())?.to_string())
1490}
1491
1492/// Multibase SHA-256 of the JCS-canonical report.
1493pub fn report_digest(report_json: &str) -> Result<String> {
1494    Ok(r::report_digest(&parse(report_json)?))
1495}
1496
1497/// Build a signed `RobotConformanceAttestation`. `params_json` is `{issuerDid,
1498/// robotDid, report, validFrom, validUntil?}` where `report` comes from
1499/// [`check_conformance`].
1500pub fn build_conformance_attestation(signer_seed: &[u8], params_json: &str) -> Result<String> {
1501    let p = parse(params_json)?;
1502    let params = r::BuildConformanceAttestation {
1503        issuer_did: gs(&p, "issuerDid")?,
1504        robot_did: gs(&p, "robotDid")?,
1505        report: p.get("report").cloned().unwrap_or(Value::Null),
1506        valid_from: gs(&p, "validFrom")?,
1507        valid_until: gos(&p, "validUntil")?,
1508    };
1509    Ok(r::build_conformance_attestation(signer_seed, &params)?.to_string())
1510}
1511
1512pub fn verify_conformance_attestation(
1513    credential_json: &str,
1514    public_key: &[u8],
1515    issuer_did: Option<&str>,
1516    now_iso: &str,
1517) -> Result<String> {
1518    Ok(subj(r::verify_conformance_attestation(
1519        &parse(credential_json)?,
1520        keys_for(public_key, issuer_did),
1521        None,
1522        None,
1523        now_iso,
1524    )?))
1525}
1526// ---- post-quantum robot credentials --------------------------------------
1527
1528pub fn sign_pq(
1529    credential_json: &str,
1530    ed25519_seed: &[u8],
1531    mldsa_secret: &[u8],
1532    mldsa_public: &[u8],
1533    created: &str,
1534) -> Result<String> {
1535    let ml = crate::pq::MlDsa44KeyPair::from_bytes(mldsa_secret, mldsa_public)?;
1536    Ok(r::sign_pq(&parse(credential_json)?, ed25519_seed, &ml, created)?.to_string())
1537}
1538
1539pub fn is_pq(credential_json: &str) -> Result<bool> {
1540    Ok(r::is_pq(&parse(credential_json)?))
1541}
1542
1543/// Verify a hybrid robot credential. `mldsa44_public` is raw 1312-byte bytes or
1544/// an ML-DSA-44 Multikey string carried as UTF-8 bytes.
1545pub fn verify_pq(
1546    credential_json: &str,
1547    ed25519_public: &[u8],
1548    mldsa44_public: &[u8],
1549) -> Result<bool> {
1550    let resolved = r::resolve_mldsa44_public(mldsa44_public)?;
1551    r::verify_pq(&parse(credential_json)?, ed25519_public, &resolved)
1552}
1553
1554/// Dual verify auto-detected from the proof. `mldsa44_public`, when present, is
1555/// raw 1312-byte bytes or an ML-DSA-44 Multikey string carried as UTF-8 bytes; a
1556/// hybrid credential requires it, a classical credential ignores it.
1557pub fn verify_robot_credential(
1558    credential_json: &str,
1559    ed25519_public: &[u8],
1560    mldsa44_public: Option<&[u8]>,
1561    issuer_did: Option<&str>,
1562    now_iso: &str,
1563) -> Result<bool> {
1564    let cred = parse(credential_json)?;
1565    // An ML-DSA-44 source given as a JSON object is a {did: multikey} map.
1566    // Input of exactly the raw key length is always the raw key: a raw key
1567    // may begin with the byte `{`, and a map that names any key is longer
1568    // (one ML-DSA-44 Multikey alone is 1,796 characters).
1569    if let Some(raw) = mldsa44_public
1570        .filter(|b| b.len() != crate::pq::MLDSA44_PUBLIC_LEN && b.first() == Some(&b'{'))
1571    {
1572        crate::nesting::check_text(raw)?;
1573        let m: Value = serde_json::from_slice(raw)
1574            .map_err(|e| CoreError::Json(format!("mldsa44 key map: {e}")))?;
1575        let mut map = alloc::collections::BTreeMap::new();
1576        for (d, k) in m.as_object().into_iter().flatten() {
1577            let k = k
1578                .as_str()
1579                .ok_or_else(|| CoreError::Json("mldsa44 key map values must be strings".into()))?;
1580            map.insert(d.clone(), k.as_bytes().to_vec());
1581        }
1582        return r::verify_robot_credential_keyed(
1583            &cred,
1584            keys_self(ed25519_public, issuer_did),
1585            Some(Keys::Map(&map)),
1586            None,
1587            now_iso,
1588        );
1589    }
1590    r::verify_robot_credential(
1591        &cred,
1592        keys_self(ed25519_public, issuer_did),
1593        mldsa44_public,
1594        None,
1595        now_iso,
1596    )
1597}
1598pub fn migrate_to_pq(
1599    credential_json: &str,
1600    ed25519_seed: &[u8],
1601    mldsa_secret: &[u8],
1602    mldsa_public: &[u8],
1603    created: &str,
1604) -> Result<String> {
1605    let ml = crate::pq::MlDsa44KeyPair::from_bytes(mldsa_secret, mldsa_public)?;
1606    Ok(r::migrate_to_pq(&parse(credential_json)?, ed25519_seed, &ml, created)?.to_string())
1607}
1608
1609// ---- cross-embodiment identity continuity ---------------------------------
1610
1611pub fn build_embodiment(agent_seed: &[u8], params_json: &str) -> Result<String> {
1612    let p = parse(params_json)?;
1613    let params = r::BuildEmbodiment {
1614        agent_did: gs(&p, "agentDid")?,
1615        body_did: gs(&p, "body")?,
1616        body_hardware_root: gs(&p, "bodyHardwareRoot")?,
1617        from_body: gos(&p, "fromBody")?,
1618        embodied_at: gs(&p, "embodiedAt")?,
1619        valid_until: gos(&p, "validUntil")?,
1620    };
1621    Ok(r::build_embodiment(agent_seed, &params)?.to_string())
1622}
1623
1624pub fn verify_embodiment(
1625    credential_json: &str,
1626    agent_public_key: &[u8],
1627    issuer_did: Option<&str>,
1628    now_iso: &str,
1629) -> Result<String> {
1630    Ok(subj(r::verify_embodiment(
1631        &parse(credential_json)?,
1632        keys_self(agent_public_key, issuer_did),
1633        None,
1634        now_iso,
1635    )?))
1636}
1637/// Verify a continuity chain under one agent key. `params_json` is
1638/// `{embodiments: [...], originBody?, agentDid?, bodyHardwareRoots?: {body:
1639/// rootMb}, now?}`; `agent_public_key` is the agent's Ed25519 public key,
1640/// trusted for `agentDid` (or, without one, only for a did:key agent).
1641/// Returns `{ok, currentBody}`.
1642pub fn verify_continuity_chain(
1643    params_json: &str,
1644    agent_public_key: &[u8],
1645    host_now: &str,
1646) -> Result<String> {
1647    let p = parse(params_json)?;
1648    let embodiments: Vec<Value> = garr(&p, "embodiments")?;
1649    let origin = gos(&p, "originBody")?;
1650    let agent = gos(&p, "agentDid")?;
1651    let roots: Option<alloc::collections::BTreeMap<String, String>> =
1652        match p.get("bodyHardwareRoots") {
1653            None | Some(Value::Null) => None,
1654            Some(Value::Object(o)) => Some(
1655                o.iter()
1656                    .map(|(k, v)| {
1657                        v.as_str()
1658                            .map(|s| (k.clone(), s.to_string()))
1659                            .ok_or_else(|| wrong_type("bodyHardwareRoots", "an object of strings"))
1660                    })
1661                    .collect::<Result<_>>()?,
1662            ),
1663            Some(_) => return Err(wrong_type("bodyHardwareRoots", "an object")),
1664        };
1665    let now = now_or(&p, host_now)?;
1666    let (ok, current) = r::verify_continuity_chain(
1667        &embodiments,
1668        keys_self(agent_public_key, agent.as_deref()),
1669        origin.as_deref(),
1670        roots.as_ref(),
1671        &now,
1672    )?;
1673    Ok(json!({"ok": ok, "currentBody": current}).to_string())
1674}
1675/// Check that no two embodiments place the agent in different bodies with
1676/// overlapping active windows. `params_json` is `{embodiments: [...]}`. Returns
1677/// `{ok, conflict}` where conflict, when present, is `{bodyA, bodyB}`.
1678pub fn check_no_fork(params_json: &str) -> Result<String> {
1679    check_no_fork_with(params_json, LogLimits::DEFAULT)
1680}
1681
1682pub(crate) fn check_no_fork_with(params_json: &str, limits: LogLimits) -> Result<String> {
1683    let p = parse_long_with(params_json, limits)?;
1684    let embodiments: Vec<Value> = garr(&p, "embodiments")?;
1685    let (ok, conflict) = r::check_no_fork(&embodiments)?;
1686    let conflict_json = conflict
1687        .map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b}))
1688        .unwrap_or(Value::Null);
1689    Ok(json!({"ok": ok, "conflict": conflict_json}).to_string())
1690}
1691
1692// ---- physical custody handoff ---------------------------------------------
1693
1694fn actor_keys(v: &Value) -> Result<Vec<r::ActorKey>> {
1695    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1696    use base64::Engine;
1697    let mut keys: Vec<r::ActorKey> = Vec::new();
1698    if !v.is_null() && !v.is_object() {
1699        return Err(wrong_type("publicKeys", "an object"));
1700    }
1701    if let Some(obj) = v.as_object() {
1702        for (did, key) in obj {
1703            let b64 = key
1704                .as_str()
1705                .ok_or_else(|| CoreError::Json("publicKeys values must be base64url".into()))?;
1706            let public_key = URL_SAFE_NO_PAD
1707                .decode(b64)
1708                .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
1709            keys.push(r::ActorKey {
1710                did: did.clone(),
1711                public_key,
1712            });
1713        }
1714    }
1715    Ok(keys)
1716}
1717
1718pub fn build_handoff(receiver_seed: &[u8], params_json: &str) -> Result<String> {
1719    let p = parse(params_json)?;
1720    let params = r::BuildHandoff {
1721        task_id: gs(&p, "taskId")?,
1722        from_actor: gs(&p, "fromActor")?,
1723        to_actor: gs(&p, "toActor")?,
1724        condition: gos(&p, "condition")?,
1725        handoff_at: gs(&p, "handoffAt")?,
1726        valid_until: gos(&p, "validUntil")?,
1727        release: p.get("release").filter(|v| !v.is_null()).cloned(),
1728        prev_handoff_id: gos(&p, "prevHandoffId")?,
1729        credential_id: gs(&p, "credentialId")?,
1730    };
1731    Ok(r::build_handoff(receiver_seed, &params)?.to_string())
1732}
1733
1734/// Build a signed custody release. `params_json` is `{releaserDid, taskId,
1735/// toActor, releasedAt}`.
1736pub fn build_release(releaser_seed: &[u8], params_json: &str) -> Result<String> {
1737    let p = parse(params_json)?;
1738    Ok(r::build_release(
1739        releaser_seed,
1740        &gs(&p, "releaserDid")?,
1741        &gs(&p, "taskId")?,
1742        &gs(&p, "toActor")?,
1743        &gs(&p, "releasedAt")?,
1744    )?
1745    .to_string())
1746}
1747
1748pub fn verify_handoff(
1749    credential_json: &str,
1750    receiver_public_key: &[u8],
1751    issuer_did: Option<&str>,
1752    now_iso: &str,
1753) -> Result<String> {
1754    Ok(subj(r::verify_handoff(
1755        &parse(credential_json)?,
1756        keys_self(receiver_public_key, issuer_did),
1757        r::HandoffCheck::default(),
1758        now_iso,
1759    )?))
1760}
1761/// Verify a custody chain. `params_json` is `{handoffs: [...], publicKeys: {did:
1762/// keyB64url, ...}, taskId, originActor?, requireRelease? (default true),
1763/// now?}` where each `publicKeys` value is an actor's Ed25519 public key as a
1764/// base64url-no-pad string. Returns `{ok, currentHolder}`.
1765pub fn verify_handoff_chain(params_json: &str, host_now: &str) -> Result<String> {
1766    let p = parse(params_json)?;
1767    let handoffs: Vec<Value> = garr(&p, "handoffs")?;
1768    let keys = actor_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
1769    let origin = gos(&p, "originActor")?;
1770    let task = gs(&p, "taskId")?;
1771    let require_release = match p.get("requireRelease") {
1772        None | Some(Value::Null) => true,
1773        Some(Value::Bool(b)) => *b,
1774        Some(_) => return Err(wrong_type("requireRelease", "true or false")),
1775    };
1776    let now = now_or(&p, host_now)?;
1777    let (ok, current) = r::verify_handoff_chain(
1778        &handoffs,
1779        &keys,
1780        &task,
1781        origin.as_deref(),
1782        require_release,
1783        &now,
1784    )?;
1785    Ok(json!({"ok": ok, "currentHolder": current}).to_string())
1786}
1787/// Return the actor holding the task at ISO time `at`. `params_json` is
1788/// `{handoffs: [...], at}`. Returns `{holder}` where holder is the actor DID or
1789/// null.
1790pub fn holder_at(params_json: &str) -> Result<String> {
1791    let p = parse(params_json)?;
1792    let handoffs: Vec<Value> = garr(&p, "handoffs")?;
1793    let at = gs(&p, "at")?;
1794    let holder = r::holder_at(&handoffs, &at);
1795    Ok(json!({"holder": holder}).to_string())
1796}
1797
1798/// Localize the first attested condition change. `params_json` is `{handoffs:
1799/// [...]}`. Returns `{change}` where change, when present, is `{responsibleHolder,
1800/// fromCondition, toCondition}`, else null.
1801pub fn locate_condition_change(params_json: &str) -> Result<String> {
1802    let p = parse(params_json)?;
1803    let handoffs: Vec<Value> = garr(&p, "handoffs")?;
1804    let change = r::locate_condition_change(&handoffs)
1805        .map(|c| {
1806            json!({
1807                "responsibleHolder": c.responsible_holder,
1808                "fromCondition": c.from_condition,
1809                "toCondition": c.to_condition,
1810            })
1811        })
1812        .unwrap_or(Value::Null);
1813    Ok(json!({"change": change}).to_string())
1814}
1815
1816// ---- robot-to-infrastructure bounded access -------------------------------
1817
1818pub fn build_access_grant(operator_seed: &[u8], params_json: &str) -> Result<String> {
1819    let p = parse(params_json)?;
1820    let params = r::BuildAccessGrant {
1821        operator_did: gs(&p, "operatorDid")?,
1822        robot_did: gs(&p, "robotDid")?,
1823        resource: gs(&p, "resource")?,
1824        operations: gstrs(&p, "operations")?,
1825        zone: gos(&p, "zone")?,
1826        granted_at: gs(&p, "grantedAt")?,
1827        valid_until: gos(&p, "validUntil")?,
1828    };
1829    Ok(r::build_access_grant(operator_seed, &params)?.to_string())
1830}
1831
1832/// Verify an access grant. `params_json` is `{grant: {...}, operatorDid?, now?}`
1833/// (the key is trusted for `operatorDid`; without it, only for a did:key
1834/// operator) or the bare
1835/// grant). Without `now`, the window is checked against `host_now`, the host
1836/// clock the wrapper supplies. Returns the credentialSubject on success, the
1837/// JSON literal `null` if invalid.
1838pub fn verify_access_grant(
1839    credential_json: &str,
1840    operator_public_key: &[u8],
1841    host_now: &str,
1842) -> Result<String> {
1843    let p = parse(credential_json)?;
1844    let (grant, now, operator, trusted) = match p.get("grant") {
1845        Some(g) => (
1846            g.clone(),
1847            now_or(&p, host_now)?,
1848            gos(&p, "operatorDid")?,
1849            gostrs(&p, "trustedOperators")?.map(|v| v.into_iter().collect::<HashSet<_>>()),
1850        ),
1851        None => (p.clone(), host_now.to_string(), None, None),
1852    };
1853    // An empty operator key is no key source: the grant then verifies only
1854    // when its did:key operator is in `trustedOperators`.
1855    Ok(subj(r::verify_access_grant(
1856        &grant,
1857        keys_for(operator_public_key, operator.as_deref()),
1858        trusted.as_ref(),
1859        &now,
1860    )?))
1861}
1862
1863pub fn build_access_request(robot_seed: &[u8], params_json: &str) -> Result<String> {
1864    let p = parse(params_json)?;
1865    let params = r::BuildAccessRequest {
1866        robot_did: gs(&p, "robotDid")?,
1867        resource: gs(&p, "resource")?,
1868        operation: gs(&p, "operation")?,
1869        requested_at: gs(&p, "requestedAt")?,
1870        nonce: gs(&p, "nonce")?,
1871    };
1872    Ok(r::build_access_request(robot_seed, &params)?.to_string())
1873}
1874
1875/// Decide, offline, whether to allow the requested access. `params_json` is
1876/// `{grant: {...}, request: {...}, operatorDid?, robotDid?, seenNonces?: [...],
1877/// now?}` (each key is
1878/// trusted for the named DID; without one, only for a did:key party). Without
1879/// `now`, the grant window is
1880/// checked against `host_now`, the host clock the wrapper supplies. The request
1881/// must be at most 60 s old and its nonce not in `seenNonces`. Returns `{ok,
1882/// reasons, nonce}`; record `nonce` when `ok`.
1883pub fn authorize_access(
1884    params_json: &str,
1885    operator_public_key: &[u8],
1886    robot_public_key: &[u8],
1887    host_now: &str,
1888) -> Result<String> {
1889    let p = parse(params_json)?;
1890    let grant = p.get("grant").cloned().unwrap_or(Value::Null);
1891    let request = p.get("request").cloned().unwrap_or(Value::Null);
1892    let now = now_or(&p, host_now)?;
1893    let operator = gos(&p, "operatorDid")?;
1894    let robot = gos(&p, "robotDid")?;
1895    // The facade holds no state: the caller passes the nonces it has already
1896    // accepted and records the returned nonce when access is allowed.
1897    let mut seen: HashSet<String> = gstrs(&p, "seenNonces")?.into_iter().collect();
1898    let before = seen.clone();
1899    let trusted: Option<HashSet<String>> =
1900        gostrs(&p, "trustedOperators")?.map(|v| v.into_iter().collect());
1901    let mut replay = r::RequestReplay::new(&mut seen);
1902    replay.trusted_operators = trusted.as_ref();
1903    if let Some(age) = oint(&p, "maxRequestAgeSeconds")? {
1904        replay.max_age_seconds = age;
1905    }
1906    if let Some(skew) = oint(&p, "clockSkewSeconds")? {
1907        replay.clock_skew_seconds = skew;
1908    }
1909    let res = r::authorize_access(
1910        &grant,
1911        &request,
1912        keys_for(operator_public_key, operator.as_deref()),
1913        keys_self(robot_public_key, robot.as_deref()),
1914        replay,
1915        &now,
1916    )?;
1917    let nonce = seen.difference(&before).next().cloned();
1918    Ok(json!({"ok": res.ok, "reasons": res.reasons, "nonce": nonce}).to_string())
1919}
1920
1921/// Return true if `child` is a valid attenuation of `parent`. `params_json` is
1922/// `{parent: {...}, child: {...}}`. Returns `{ok}`.
1923pub fn attenuates_grant(params_json: &str) -> Result<String> {
1924    let p = parse(params_json)?;
1925    let parent = p.get("parent").cloned().unwrap_or(Value::Null);
1926    let child = p.get("child").cloned().unwrap_or(Value::Null);
1927    let ok = r::attenuates_grant(&parent, &child);
1928    Ok(json!({"ok": ok}).to_string())
1929}
1930
1931// ---- fused-sensor provenance ----------------------------------------------
1932
1933/// Deterministic multibase digest over an ordered list of input frame hashes.
1934/// `params_json` is `{inputFrameHashes: [...], version?}` (version "2", the
1935/// JCS array digest, by default; "1" is the legacy newline join).
1936pub fn fusion_inputs_digest(params_json: &str) -> Result<String> {
1937    let p = parse(params_json)?;
1938    let version = gos(&p, "version")?.unwrap_or_else(|| r::INPUTS_DIGEST_V2.to_string());
1939    r::fusion_inputs_digest_version(&gstrs(&p, "inputFrameHashes")?, &version)
1940}
1941
1942/// Multibase SHA-256 of a raw fused output.
1943pub fn hash_fused_output(output: &[u8]) -> String {
1944    r::hash_fused_output(output)
1945}
1946
1947/// Build a signed fused-perception attestation. `params_json` is `{robotDid,
1948/// fusionMethod, inputFrameHashes, fusedOutputMb?|fusedOutputHash?, capturedAt?,
1949/// validFrom, validUntil?}` where `fusedOutputMb` is a multibase-encoded raw
1950/// output.
1951pub fn build_fused_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
1952    let p = parse(params_json)?;
1953    let fused_output = match gos(&p, "fusedOutputMb")? {
1954        Some(mb) if !mb.is_empty() => Some(r::unmb64(&mb)?),
1955        _ => None,
1956    };
1957    let params = r::BuildFusedAttestation {
1958        robot_did: gs(&p, "robotDid")?,
1959        fusion_method: gs(&p, "fusionMethod")?,
1960        input_frame_hashes: gstrs(&p, "inputFrameHashes")?,
1961        fused_output,
1962        fused_output_hash: gos(&p, "fusedOutputHash")?,
1963        captured_at: gos(&p, "capturedAt")?,
1964        valid_from: gs(&p, "validFrom")?,
1965        valid_until: gos(&p, "validUntil")?,
1966    };
1967    Ok(r::build_fused_attestation(robot_seed, &params)?.to_string())
1968}
1969
1970/// Verify a fused-perception attestation. When `fused_output_mb` is a non-empty
1971/// multibase string, the raw fused output is decoded and its hash compared to the
1972/// attested value. Returns the credentialSubject on success, `null` if invalid.
1973pub fn verify_fused_attestation(
1974    credential_json: &str,
1975    public_key: &[u8],
1976    fused_output_mb: Option<&str>,
1977    issuer_did: Option<&str>,
1978    now_iso: &str,
1979) -> Result<String> {
1980    let fused_output = match fused_output_mb {
1981        Some(mb) if !mb.is_empty() => Some(r::unmb64(mb)?),
1982        _ => None,
1983    };
1984    Ok(subj(r::verify_fused_attestation(
1985        &parse(credential_json)?,
1986        keys_self(public_key, issuer_did),
1987        fused_output.as_deref(),
1988        now_iso,
1989    )?))
1990}
1991
1992/// Confirm every input frame the attestation names was recorded in the robot's
1993/// perception log. `params_json` is `{credential: {...}, logEntries: [...]}`.
1994/// Returns `{ok, missing}`.
1995pub fn verify_fusion_inputs(params_json: &str) -> Result<String> {
1996    let p = parse(params_json)?;
1997    let credential = p.get("credential").cloned().unwrap_or(Value::Null);
1998    let entries = garr(&p, "logEntries")?;
1999    let res = r::verify_fusion_inputs(&credential, &entries);
2000    Ok(json!({"ok": res.ok, "missing": res.missing}).to_string())
2001}
2002
2003// ---- wear and degradation attestation -------------------------------------
2004
2005/// Build a signed wear attestation. `params_json` is `{robotDid, wearLevel,
2006/// metrics?, prevProof?, attestedAt?, validFrom, validUntil?}` where `metrics`, if
2007/// present, is an object carried through into the subject unchanged.
2008pub fn build_wear_attestation(robot_seed: &[u8], params_json: &str) -> Result<String> {
2009    let p = parse(params_json)?;
2010    let params = r::BuildWearAttestation {
2011        robot_did: gs(&p, "robotDid")?,
2012        wear_level: gof(&p, "wearLevel")?.unwrap_or(0.0),
2013        metrics: p.get("metrics").filter(|v| !v.is_null()).cloned(),
2014        prev_proof: gos(&p, "prevProof")?,
2015        attested_at: gos(&p, "attestedAt")?,
2016        valid_from: gs(&p, "validFrom")?,
2017        valid_until: gos(&p, "validUntil")?,
2018    };
2019    Ok(r::build_wear_attestation(robot_seed, &params)?.to_string())
2020}
2021
2022/// Verify a wear attestation. Returns the credentialSubject on success, `null` if
2023/// invalid.
2024pub fn verify_wear_attestation(
2025    credential_json: &str,
2026    public_key: &[u8],
2027    issuer_did: Option<&str>,
2028    now_iso: &str,
2029) -> Result<String> {
2030    Ok(subj(r::verify_wear_attestation(
2031        &parse(credential_json)?,
2032        keys_self(public_key, issuer_did),
2033        now_iso,
2034    )?))
2035}
2036
2037/// Verify an ordered wear history. `params_json` is `{attestations: [...],
2038/// robotDid?, now?}` (the key is trusted for `robotDid`; without it, only for a
2039/// did:key robot).
2040/// Returns `{ok, latest}` where `latest`, when `ok`, is the latest
2041/// credentialSubject.
2042pub fn verify_wear_chain(params_json: &str, public_key: &[u8], host_now: &str) -> Result<String> {
2043    let p = parse(params_json)?;
2044    let attestations: Vec<Value> = garr(&p, "attestations")?;
2045    let robot = gos(&p, "robotDid")?;
2046    let now = now_or(&p, host_now)?;
2047    let latest =
2048        r::verify_wear_chain(&attestations, keys_self(public_key, robot.as_deref()), &now)?;
2049    Ok(json!({"ok": latest.is_some(), "latest": latest}).to_string())
2050}
2051
2052/// Derive a physical scope narrowed for a wear level. `params_json` is `{scope:
2053/// {...}, wearLevel}`. Returns the narrowed scope JSON.
2054pub fn attenuate_for_wear(params_json: &str) -> Result<String> {
2055    let p = parse(params_json)?;
2056    let scope = p.get("scope").cloned().unwrap_or(Value::Null);
2057    let wear_level =
2058        gof(&p, "wearLevel")?.ok_or_else(|| wrong_type("wearLevel", "a number from 0.0 to 1.0"))?;
2059    Ok(r::attenuate_for_wear(&scope, wear_level)?.to_string())
2060}
2061
2062// ---- bystander-consent evidence -------------------------------------------
2063
2064/// Multibase SHA-256 of a raw capture.
2065pub fn hash_capture(capture: &[u8]) -> String {
2066    r::hash_capture(capture)
2067}
2068
2069/// Build a signed bystander consent token. `params_json` is `{bystanderDid,
2070/// captureHash, robotDid, scope?, grantedAt, validUntil?}`.
2071pub fn build_consent_token(bystander_seed: &[u8], params_json: &str) -> Result<String> {
2072    let p = parse(params_json)?;
2073    let params = r::BuildConsentToken {
2074        bystander_did: gs(&p, "bystanderDid")?,
2075        capture_hash: gs(&p, "captureHash")?,
2076        robot_did: gs(&p, "robotDid")?,
2077        scope: gos(&p, "scope")?,
2078        granted_at: gs(&p, "grantedAt")?,
2079        valid_until: gos(&p, "validUntil")?,
2080    };
2081    Ok(r::build_consent_token(bystander_seed, &params)?.to_string())
2082}
2083
2084/// Verify a bystander consent token bound to a capture and a robot. `params_json`
2085/// is `{token: {...}, captureHash, robotDid, bystanderDid?, now?}` (the key is
2086/// trusted for `bystanderDid`; without it, only for a did:key bystander). Returns the credentialSubject
2087/// on success, `null` if invalid. Without `now`, the window is checked against
2088/// `host_now`, the host clock the wrapper supplies.
2089pub fn verify_consent_token(
2090    params_json: &str,
2091    bystander_public_key: &[u8],
2092    host_now: &str,
2093) -> Result<String> {
2094    let p = parse(params_json)?;
2095    let token = p.get("token").cloned().unwrap_or(Value::Null);
2096    let bystander = gos(&p, "bystanderDid")?;
2097    Ok(subj(r::verify_consent_token(
2098        &token,
2099        keys_self(bystander_public_key, bystander.as_deref()),
2100        &gs(&p, "captureHash")?,
2101        &gs(&p, "robotDid")?,
2102        &now_or(&p, host_now)?,
2103    )?))
2104}
2105
2106/// Build a signed bystander-consent evidence credential. `params_json` is
2107/// `{robotDid, captureHash, basis, consentTokens?, redactionHash?, validFrom,
2108/// validUntil?}` where `consentTokens` is a list of signed token credentials.
2109pub fn build_consent_evidence(robot_seed: &[u8], params_json: &str) -> Result<String> {
2110    let p = parse(params_json)?;
2111    let consent_tokens = garr(&p, "consentTokens")?;
2112    let params = r::BuildConsentEvidence {
2113        robot_did: gs(&p, "robotDid")?,
2114        capture_hash: gs(&p, "captureHash")?,
2115        basis: gs(&p, "basis")?,
2116        consent_tokens,
2117        redaction_hash: gos(&p, "redactionHash")?,
2118        valid_from: gs(&p, "validFrom")?,
2119        valid_until: gos(&p, "validUntil")?,
2120    };
2121    Ok(r::build_consent_evidence(robot_seed, &params)?.to_string())
2122}
2123
2124/// Verify a bystander-consent evidence credential. `params_json` is `{evidence:
2125/// {...}, robotDid?, captureMb?, consentTokens?, bystanderKeys?, now?}` (the
2126/// robot key is trusted for `robotDid`; without it, only for a did:key robot) where `captureMb` is
2127/// the multibase-encoded raw capture and `bystanderKeys` maps a bystander DID to
2128/// its multibase public key. Returns the credentialSubject on success, `null` if
2129/// invalid. Without `now`, token windows are checked against `host_now`, the
2130/// host clock the wrapper supplies.
2131pub fn verify_consent_evidence(
2132    params_json: &str,
2133    robot_public_key: &[u8],
2134    host_now: &str,
2135) -> Result<String> {
2136    let p = parse(params_json)?;
2137    let evidence = p.get("evidence").cloned().unwrap_or(Value::Null);
2138    let capture = match gos(&p, "captureMb")? {
2139        Some(mb) if !mb.is_empty() => Some(r::unmb64(&mb)?),
2140        _ => None,
2141    };
2142    let consent_tokens = goarr(&p, "consentTokens")?;
2143    let bystander_keys = match present(&p, "bystanderKeys") {
2144        Some(Value::Object(map)) => {
2145            let mut keys = Vec::with_capacity(map.len());
2146            for (did, mb) in map {
2147                let mb = mb
2148                    .as_str()
2149                    .ok_or_else(|| wrong_type("bystanderKeys values", "multibase strings"))?;
2150                keys.push(r::BystanderKey {
2151                    did: did.clone(),
2152                    public_key: r::unmb64(mb)?,
2153                });
2154            }
2155            Some(keys)
2156        }
2157        Some(_) => return Err(wrong_type("bystanderKeys", "an object")),
2158        None => None,
2159    };
2160    let robot = gos(&p, "robotDid")?;
2161    Ok(subj(r::verify_consent_evidence(
2162        &evidence,
2163        keys_self(robot_public_key, robot.as_deref()),
2164        capture.as_deref(),
2165        consent_tokens.as_deref(),
2166        bystander_keys.as_deref(),
2167        &now_or(&p, host_now)?,
2168    )?))
2169}
2170
2171// ---- parity functions: ODD, handover, validity witness, snapshot freshness ----
2172//
2173// Each verify facade takes one params object carrying the credential(s), a
2174// `publicKeys` map `{did: base64url raw Ed25519 key}` and an optional `now`
2175// (else `host_now`, the wrapper's clock). Each builder takes the signer seed
2176// and a params object. Every result is a JSON object.
2177
2178fn pk_map(p: &Value) -> Result<alloc::collections::BTreeMap<String, Vec<u8>>> {
2179    let keys = owner_keys(p.get("publicKeys").unwrap_or(&Value::Null))?;
2180    Ok(Keys::map_of(
2181        keys.into_iter().map(|k| (k.did, k.public_key)),
2182    ))
2183}
2184
2185fn field(p: &Value, k: &str) -> Value {
2186    p.get(k).cloned().unwrap_or(Value::Null)
2187}
2188
2189/// Build an `OperatingDomainCredential`. `{operatorDid, robotDid, domain,
2190/// validFrom, validUntil?}`.
2191pub fn build_odd_credential(operator_seed: &[u8], params_json: &str) -> Result<String> {
2192    let p = parse(params_json)?;
2193    Ok(crate::robotics_domain::build_odd_credential(
2194        operator_seed,
2195        &gs(&p, "operatorDid")?,
2196        &gs(&p, "robotDid")?,
2197        &field(&p, "domain"),
2198        &gs(&p, "validFrom")?,
2199        gos(&p, "validUntil")?.as_deref(),
2200    )?
2201    .to_string())
2202}
2203
2204/// `{credential, publicKeys, robotDid?, trustedOperators?, now?}` ->
2205/// `{ok, domain}`.
2206pub fn verify_odd_credential(params_json: &str, host_now: &str) -> Result<String> {
2207    let p = parse(params_json)?;
2208    let map = pk_map(&p)?;
2209    let trusted: Option<HashSet<String>> =
2210        gostrs(&p, "trustedOperators")?.map(|v| v.into_iter().collect());
2211    let d = crate::robotics_domain::verify_odd_credential(
2212        &field(&p, "credential"),
2213        Keys::Map(&map),
2214        gos(&p, "robotDid")?.as_deref(),
2215        trusted.as_ref(),
2216        &now_or(&p, host_now)?,
2217    )?;
2218    Ok(json!({"ok": d.is_some(), "domain": d}).to_string())
2219}
2220
2221/// `{domain, observed}` -> `{ok, reasons}`.
2222pub fn check_in_domain(params_json: &str) -> Result<String> {
2223    let p = parse(params_json)?;
2224    let r = crate::robotics_domain::check_in_domain(&field(&p, "domain"), &field(&p, "observed"));
2225    Ok(json!({"ok": r.ok, "reasons": r.reasons}).to_string())
2226}
2227
2228/// Build an `ODDConformanceAttestation`. `{robotDid, domain, observed,
2229/// intervalIndex, validFrom, validUntil?}`.
2230pub fn build_odd_conformance(robot_seed: &[u8], params_json: &str) -> Result<String> {
2231    let p = parse(params_json)?;
2232    Ok(crate::robotics_domain::build_odd_conformance(
2233        robot_seed,
2234        &gs(&p, "robotDid")?,
2235        &field(&p, "domain"),
2236        &field(&p, "observed"),
2237        gi(&p, "intervalIndex")?,
2238        &gs(&p, "validFrom")?,
2239        gos(&p, "validUntil")?.as_deref(),
2240    )?
2241    .to_string())
2242}
2243
2244/// `{credential, publicKeys, domain, now?}` -> `{ok, subject}`.
2245pub fn verify_odd_conformance(params_json: &str, host_now: &str) -> Result<String> {
2246    let p = parse(params_json)?;
2247    let map = pk_map(&p)?;
2248    let s = crate::robotics_domain::verify_odd_conformance(
2249        &field(&p, "credential"),
2250        Keys::Map(&map),
2251        &field(&p, "domain"),
2252        &now_or(&p, host_now)?,
2253    )?;
2254    Ok(json!({"ok": s.is_some(), "subject": s}).to_string())
2255}
2256
2257/// Build a `HumanHandoverCredential`. `{robotDid, recipient, objectId, forceN,
2258/// speedMps, scope?, validFrom, validUntil?}`.
2259pub fn build_human_handover(robot_seed: &[u8], params_json: &str) -> Result<String> {
2260    let p = parse(params_json)?;
2261    let params = crate::robotics_domain::BuildHumanHandover {
2262        robot_did: gs(&p, "robotDid")?,
2263        recipient: gs(&p, "recipient")?,
2264        object_id: gs(&p, "objectId")?,
2265        force_n: gof(&p, "forceN")?.ok_or_else(|| wrong_type("forceN", "a number"))?,
2266        speed_mps: gof(&p, "speedMps")?.ok_or_else(|| wrong_type("speedMps", "a number"))?,
2267        scope: p.get("scope").filter(|v| !v.is_null()).cloned(),
2268        valid_from: gs(&p, "validFrom")?,
2269        valid_until: gos(&p, "validUntil")?,
2270    };
2271    Ok(crate::robotics_domain::build_human_handover(robot_seed, &params)?.to_string())
2272}
2273
2274/// `{credential, publicKeys, scope?, now?}` -> `{ok, subject}`.
2275pub fn verify_human_handover(params_json: &str, host_now: &str) -> Result<String> {
2276    let p = parse(params_json)?;
2277    let map = pk_map(&p)?;
2278    let scope = p.get("scope").filter(|v| !v.is_null()).cloned();
2279    let s = crate::robotics_domain::verify_human_handover(
2280        &field(&p, "credential"),
2281        Keys::Map(&map),
2282        scope.as_ref(),
2283        &now_or(&p, host_now)?,
2284    )?;
2285    Ok(json!({"ok": s.is_some(), "subject": s}).to_string())
2286}
2287
2288/// Build a `HandoverAcknowledgement`. `{recipientDid, handover, validFrom}`.
2289pub fn build_handover_ack(recipient_seed: &[u8], params_json: &str) -> Result<String> {
2290    let p = parse(params_json)?;
2291    Ok(crate::robotics_domain::build_handover_ack(
2292        recipient_seed,
2293        &gs(&p, "recipientDid")?,
2294        &field(&p, "handover"),
2295        &gs(&p, "validFrom")?,
2296    )?
2297    .to_string())
2298}
2299
2300/// `{credential, publicKeys, handover, now?}` -> `{ok, subject}`.
2301pub fn verify_handover_ack(params_json: &str, host_now: &str) -> Result<String> {
2302    let p = parse(params_json)?;
2303    let map = pk_map(&p)?;
2304    let s = crate::robotics_domain::verify_handover_ack(
2305        &field(&p, "credential"),
2306        Keys::Map(&map),
2307        &field(&p, "handover"),
2308        &now_or(&p, host_now)?,
2309    )?;
2310    Ok(json!({"ok": s.is_some(), "subject": s}).to_string())
2311}
2312
2313/// Sign a PAD-120 valid-set root. `{authorityDid, validIds, epoch, created}`.
2314pub fn build_validity_root(authority_seed: &[u8], params_json: &str) -> Result<String> {
2315    let p = parse(params_json)?;
2316    Ok(crate::robotics_dtn::build_validity_root(
2317        authority_seed,
2318        &gs(&p, "authorityDid")?,
2319        &gstrs(&p, "validIds")?,
2320        gi(&p, "epoch")?,
2321        &gs(&p, "created")?,
2322    )?
2323    .to_string())
2324}
2325
2326/// `{validIds, credentialId}` -> the witness object.
2327pub fn build_validity_witness(params_json: &str) -> Result<String> {
2328    let p = parse(params_json)?;
2329    Ok(crate::robotics_dtn::build_validity_witness(
2330        &gstrs(&p, "validIds")?,
2331        &gs(&p, "credentialId")?,
2332    )?
2333    .to_string())
2334}
2335
2336/// `{witness, signedRoot, publicKeys, credentialId, verifierEpoch, tier?,
2337/// maxEpochGap?, seenEpoch?, now?}` -> `{ok, epoch}`.
2338pub fn verify_validity_witness(params_json: &str, host_now: &str) -> Result<String> {
2339    let p = parse(params_json)?;
2340    let map = pk_map(&p)?;
2341    let opt_i = |k: &str| -> Result<Option<i64>> {
2342        match present(&p, k) {
2343            None => Ok(None),
2344            Some(x) => x
2345                .as_i64()
2346                .map(Some)
2347                .ok_or_else(|| wrong_type(k, "a whole number")),
2348        }
2349    };
2350    let (ok, epoch) = crate::robotics_dtn::verify_validity_witness(
2351        &field(&p, "witness"),
2352        &field(&p, "signedRoot"),
2353        Keys::Map(&map),
2354        &gs(&p, "credentialId")?,
2355        gi(&p, "verifierEpoch")?,
2356        &gos(&p, "tier")?.unwrap_or_else(|| "critical".into()),
2357        opt_i("maxEpochGap")?,
2358        opt_i("seenEpoch")?,
2359        &now_or(&p, host_now)?,
2360    )?;
2361    Ok(json!({"ok": ok, "epoch": epoch}).to_string())
2362}
2363
2364/// `{tier, credentialStatus?, snapshot?, credentialIssuer, publicKeys, now?,
2365/// budgetSeconds?, clockSkewSeconds?}` -> `{allow, tier, reason,
2366/// stalenessSeconds, budgetSeconds}`.
2367pub fn evaluate_snapshot_freshness(params_json: &str, host_now: &str) -> Result<String> {
2368    let p = parse(params_json)?;
2369    let map = pk_map(&p)?;
2370    let budget = match present(&p, "budgetSeconds") {
2371        None => None,
2372        Some(x) => Some(
2373            x.as_i64()
2374                .ok_or_else(|| wrong_type("budgetSeconds", "a whole number"))?,
2375        ),
2376    };
2377    let skew = match present(&p, "clockSkewSeconds") {
2378        None => 30,
2379        Some(x) => x
2380            .as_i64()
2381            .ok_or_else(|| wrong_type("clockSkewSeconds", "a whole number"))?,
2382    };
2383    let status = p.get("credentialStatus").filter(|v| !v.is_null()).cloned();
2384    let snapshot = p.get("snapshot").filter(|v| !v.is_null()).cloned();
2385    let v = crate::robotics_dtn::evaluate_snapshot_freshness(
2386        &gs(&p, "tier")?,
2387        status.as_ref(),
2388        snapshot.as_ref(),
2389        &gs(&p, "credentialIssuer")?,
2390        Keys::Map(&map),
2391        &now_or(&p, host_now)?,
2392        budget,
2393        skew,
2394    )?;
2395    Ok(json!({
2396        "allow": v.allow,
2397        "tier": v.tier,
2398        "reason": v.reason,
2399        "stalenessSeconds": v.staleness_seconds,
2400        "budgetSeconds": v.budget_seconds,
2401    })
2402    .to_string())
2403}
2404
2405/// `{credential, statusList, statusPurpose?, publicKeys?, now?}` -> `{result}`.
2406/// With `publicKeys` the list's signature must verify; errors (wrong list,
2407/// wrong issuer, bad signature) are returned as errors.
2408pub fn check_credential_status_signed(params_json: &str, host_now: &str) -> Result<String> {
2409    let p = parse(params_json)?;
2410    let purpose = gos(&p, "statusPurpose")?.unwrap_or_else(|| "revocation".into());
2411    let res = if present(&p, "publicKeys").is_some() {
2412        let map = pk_map(&p)?;
2413        r::check_credential_status_signed(
2414            &field(&p, "credential"),
2415            &field(&p, "statusList"),
2416            &purpose,
2417            Keys::Map(&map),
2418            &now_or(&p, host_now)?,
2419        )?
2420    } else {
2421        r::check_credential_status(&field(&p, "credential"), &field(&p, "statusList"), &purpose)?
2422    };
2423    Ok(json!({"result": res}).to_string())
2424}
2425
2426/// `{passport (object or vouch-passport: URI), publicKeys, trustedIssuers?,
2427/// now?}` -> `{ok, summary}` with the summary carrying the verified `issuer`.
2428pub fn verify_passport_summary(params_json: &str, host_now: &str) -> Result<String> {
2429    let p = parse(params_json)?;
2430    let map = pk_map(&p)?;
2431    let trusted: Option<HashSet<String>> =
2432        gostrs(&p, "trustedIssuers")?.map(|v| v.into_iter().collect());
2433    let s = r::verify_passport_summary(
2434        &field(&p, "passport"),
2435        Keys::Map(&map),
2436        trusted.as_ref(),
2437        &now_or(&p, host_now)?,
2438    )?;
2439    Ok(json!({"ok": s.is_some(), "summary": s}).to_string())
2440}
2441
2442/// Build a `SwarmMembershipCredential`. `{coordinatorDid, swarmId, robotDid,
2443/// role?, validFrom, validUntil?}`.
2444pub fn build_swarm_membership(seed: &[u8], params_json: &str) -> Result<String> {
2445    let p = parse(params_json)?;
2446    Ok(crate::robotics_domain::build_swarm_membership(
2447        seed,
2448        &gs(&p, "coordinatorDid")?,
2449        &gs(&p, "swarmId")?,
2450        &gs(&p, "robotDid")?,
2451        gos(&p, "role")?.as_deref(),
2452        &gs(&p, "validFrom")?,
2453        gos(&p, "validUntil")?.as_deref(),
2454    )?
2455    .to_string())
2456}
2457
2458/// `{credential, publicKeys, swarmId?, coordinatorDid?, now?}` -> `{ok, subject}`.
2459pub fn verify_swarm_membership(params_json: &str, host_now: &str) -> Result<String> {
2460    let p = parse(params_json)?;
2461    let map = pk_map(&p)?;
2462    let s = crate::robotics_domain::verify_swarm_membership(
2463        &field(&p, "credential"),
2464        Keys::Map(&map),
2465        gos(&p, "swarmId")?.as_deref(),
2466        gos(&p, "coordinatorDid")?.as_deref(),
2467        &now_or(&p, host_now)?,
2468    )?;
2469    Ok(json!({"ok": s.is_some(), "subject": s}).to_string())
2470}
2471
2472/// Build a `CollectiveActionAttestation`. `{coordinatorDid, swarmId, action,
2473/// participants, validFrom, validUntil?}`.
2474pub fn build_collective_action(seed: &[u8], params_json: &str) -> Result<String> {
2475    let p = parse(params_json)?;
2476    Ok(crate::robotics_domain::build_collective_action(
2477        seed,
2478        &gs(&p, "coordinatorDid")?,
2479        &gs(&p, "swarmId")?,
2480        &gs(&p, "action")?,
2481        &gstrs(&p, "participants")?,
2482        &gs(&p, "validFrom")?,
2483        gos(&p, "validUntil")?.as_deref(),
2484    )?
2485    .to_string())
2486}
2487
2488/// `{credential, publicKeys, memberships?, now?}` -> `{ok, unverified}`.
2489pub fn verify_collective_action(params_json: &str, host_now: &str) -> Result<String> {
2490    let p = parse(params_json)?;
2491    let map = pk_map(&p)?;
2492    let memberships = goarr(&p, "memberships")?;
2493    let now = now_or(&p, host_now)?;
2494    rvf::require_now(&now)?;
2495    let credential = field(&p, "credential");
2496    // With `coordinatorDid`, the action must come from that coordinator; with
2497    // no key for it, a did:key coordinator verifies under its own key.
2498    let coordinator = gos(&p, "coordinatorDid")?;
2499    if let Some(c) = &coordinator {
2500        if rvf::issuer_id(credential.get("issuer")) != Some(c.as_str()) {
2501            return Ok(json!({"ok": false, "unverified": []}).to_string());
2502        }
2503    }
2504    let keys = match &coordinator {
2505        Some(c) if !map.contains_key(c) => Keys::Pinned(c),
2506        _ => Keys::Map(&map),
2507    };
2508    let (ok, unverified) = crate::robotics_domain::verify_collective_action(
2509        &credential,
2510        keys,
2511        memberships.as_deref(),
2512        &now,
2513    )?;
2514    Ok(json!({"ok": ok, "unverified": unverified}).to_string())
2515}
2516
2517/// Build a `ControlHandoffCredential`. `{robotDid, fromController,
2518/// toController, mode, validFrom, validUntil?, prevHandoffId?, credentialId}`.
2519pub fn build_control_handoff(seed: &[u8], params_json: &str) -> Result<String> {
2520    let p = parse(params_json)?;
2521    let params = crate::robotics_domain::BuildControlHandoff {
2522        robot_did: gs(&p, "robotDid")?,
2523        from_controller: gs(&p, "fromController")?,
2524        to_controller: gs(&p, "toController")?,
2525        mode: gs(&p, "mode")?,
2526        valid_from: gs(&p, "validFrom")?,
2527        valid_until: gos(&p, "validUntil")?,
2528        prev_handoff_id: gos(&p, "prevHandoffId")?,
2529        credential_id: gs(&p, "credentialId")?,
2530    };
2531    Ok(crate::robotics_domain::build_control_handoff(seed, &params)?.to_string())
2532}
2533
2534/// `{credential, publicKeys, robotDid?, now?}` -> `{ok, subject}`.
2535pub fn verify_control_handoff(params_json: &str, host_now: &str) -> Result<String> {
2536    let p = parse(params_json)?;
2537    let map = pk_map(&p)?;
2538    let s = crate::robotics_domain::verify_control_handoff(
2539        &field(&p, "credential"),
2540        Keys::Map(&map),
2541        gos(&p, "robotDid")?.as_deref(),
2542        &now_or(&p, host_now)?,
2543    )?;
2544    Ok(json!({"ok": s.is_some(), "subject": s}).to_string())
2545}
2546
2547/// `{handoffs, publicKeys, robotDid, originController?, now?}` -> `{ok,
2548/// currentController}`.
2549pub fn verify_control_chain(params_json: &str, host_now: &str) -> Result<String> {
2550    let p = parse(params_json)?;
2551    let map = pk_map(&p)?;
2552    let (ok, cur) = crate::robotics_domain::verify_control_chain(
2553        &garr(&p, "handoffs")?,
2554        Keys::Map(&map),
2555        &gs(&p, "robotDid")?,
2556        gos(&p, "originController")?.as_deref(),
2557        &now_or(&p, host_now)?,
2558    )?;
2559    Ok(json!({"ok": ok, "currentController": if ok { cur } else { None }}).to_string())
2560}
2561
2562/// `{handoffs, at}` -> `{controller}`.
2563pub fn controller_at(params_json: &str) -> Result<String> {
2564    let p = parse(params_json)?;
2565    let c = crate::robotics_domain::controller_at(&garr(&p, "handoffs")?, &gs(&p, "at")?);
2566    Ok(json!({"controller": c}).to_string())
2567}
2568
2569/// `{handoffs}` -> `{ok, gaps, overlaps}`.
2570pub fn check_control_continuity(params_json: &str) -> Result<String> {
2571    let p = parse(params_json)?;
2572    let (ok, seams) = crate::robotics_domain::check_control_continuity(&garr(&p, "handoffs")?);
2573    Ok(json!({"ok": ok, "gaps": seams, "overlaps": seams}).to_string())
2574}
2575
2576// ---- disconnected edge, DTN and quorum trust (PAD-106 to PAD-124) ---------
2577//
2578// Every facade below follows one of three shapes so the WASM, C ABI and UniFFI
2579// layers can bind them the same way:
2580//
2581// * builders: `(seed, params_json, host_now)`. The signer's DID is a param;
2582//   `created` defaults to `host_now`.
2583// * checks: `(params_json, host_now)`. A signed input is verified against
2584//   `publicKeys` ({did: base64url raw key}; absent means only a did:key issuer
2585//   verifies, under the key inside its DID) at `now` (default `host_now`).
2586// * the result is JSON: a verified subject or `null`, a boolean, a number, a
2587//   string, or an object for a multi-part result.
2588//
2589// Threshold predicates take the signed credentials and verify them here, so a
2590// caller can never hand in "already verified" pairs it did not check.
2591
2592use crate::robotics_dtn as dtn;
2593use crate::robotics_verify as rvf;
2594
2595fn ri(v: &Value, k: &str) -> Result<i64> {
2596    oi(v, k)?.ok_or_else(|| CoreError::Json(format!("{k} is required")))
2597}
2598fn oi(v: &Value, k: &str) -> Result<Option<i64>> {
2599    match present(v, k) {
2600        None => Ok(None),
2601        Some(x) if rvf::is_strict_int(x) => Ok(x.as_i64()),
2602        Some(_) => Err(wrong_type(k, "a whole number")),
2603    }
2604}
2605fn rf(v: &Value, k: &str) -> Result<f64> {
2606    gof(v, k)?.ok_or_else(|| CoreError::Json(format!("{k} is required")))
2607}
2608fn rs(v: &Value, k: &str) -> Result<String> {
2609    gos(v, k)?.ok_or_else(|| CoreError::Json(format!("{k} is required")))
2610}
2611fn rv3(v: &Value, k: &str) -> Result<[f64; 3]> {
2612    ov3(v, k)?.ok_or_else(|| CoreError::Json(format!("{k} is required")))
2613}
2614fn ov3(v: &Value, k: &str) -> Result<Option<[f64; 3]>> {
2615    match present(v, k) {
2616        None => Ok(None),
2617        Some(Value::Array(a)) if a.len() == 3 => {
2618            let mut out = [0.0f64; 3];
2619            for (i, x) in a.iter().enumerate() {
2620                match x.as_f64() {
2621                    Some(n) if x.is_number() && n.is_finite() => out[i] = n,
2622                    _ => return Err(wrong_type(k, "three finite numbers")),
2623                }
2624            }
2625            Ok(Some(out))
2626        }
2627        Some(_) => Err(wrong_type(k, "three finite numbers")),
2628    }
2629}
2630fn rval(v: &Value, k: &str) -> Result<Value> {
2631    present(v, k)
2632        .cloned()
2633        .ok_or_else(|| CoreError::Json(format!("{k} is required")))
2634}
2635fn created_or(p: &Value, host_now: &str) -> Result<String> {
2636    Ok(gos(p, "created")?.unwrap_or_else(|| host_now.to_string()))
2637}
2638fn epoch_pair(v: &Value, k: &str) -> Result<(i64, i64)> {
2639    match present(v, k) {
2640        Some(Value::Array(a)) if a.len() == 2 && a.iter().all(rvf::is_strict_int) => {
2641            Ok((a[0].as_i64().unwrap_or(0), a[1].as_i64().unwrap_or(0)))
2642        }
2643        _ => Err(wrong_type(k, "two whole numbers")),
2644    }
2645}
2646fn str_set(v: &Value, k: &str) -> Result<HashSet<String>> {
2647    Ok(gstrs(v, k)?.into_iter().collect())
2648}
2649fn b(x: bool) -> String {
2650    Value::Bool(x).to_string()
2651}
2652
2653/// The `publicKeys` map of a request (an empty map when absent).
2654struct KeyIn {
2655    map: alloc::collections::BTreeMap<String, Vec<u8>>,
2656    given: bool,
2657}
2658impl KeyIn {
2659    fn from(p: &Value, k: &str) -> Result<Self> {
2660        let raw = p.get(k).cloned().unwrap_or(Value::Null);
2661        let given = !raw.is_null();
2662        let keys = owner_keys(&raw)?;
2663        Ok(KeyIn {
2664            map: Keys::map_of(keys.into_iter().map(|k| (k.did, k.public_key))),
2665            given,
2666        })
2667    }
2668    fn keys(&self) -> Keys<'_> {
2669        if self.given {
2670            Keys::Map(&self.map)
2671        } else {
2672            Keys::Embedded
2673        }
2674    }
2675}
2676
2677/// The replay rules of a request: verifierEpoch, tier, maxEpochGap, seenEpoch,
2678/// expectedNonce and seenNonces. The facade is stateless: after an accepted
2679/// artifact the caller records its `credentialSubject.nonce` (and epoch).
2680struct ReplayIn {
2681    epoch: i64,
2682    tier: String,
2683    gap: Option<i64>,
2684    seen_epoch: Option<i64>,
2685    nonce: Option<String>,
2686    seen: Option<HashSet<String>>,
2687}
2688impl ReplayIn {
2689    fn from(p: &Value, default_tier: &str, epoch_required: bool) -> Result<Self> {
2690        Ok(ReplayIn {
2691            epoch: if epoch_required {
2692                ri(p, "verifierEpoch")?
2693            } else {
2694                oi(p, "verifierEpoch")?.unwrap_or(0)
2695            },
2696            tier: gos(p, "tier")?.unwrap_or_else(|| default_tier.to_string()),
2697            gap: oi(p, "maxEpochGap")?,
2698            seen_epoch: oi(p, "seenEpoch")?,
2699            nonce: gos(p, "expectedNonce")?,
2700            seen: gostrs(p, "seenNonces")?.map(|v| v.into_iter().collect()),
2701        })
2702    }
2703    fn replay(&mut self) -> dtn::Replay<'_> {
2704        dtn::Replay {
2705            verifier_epoch: self.epoch,
2706            tier: &self.tier,
2707            max_epoch_gap: self.gap,
2708            seen_epoch: self.seen_epoch,
2709            expected_nonce: self.nonce.as_deref(),
2710            seen_nonces: self.seen.as_mut(),
2711        }
2712    }
2713}
2714
2715/// Verify `credentials` (field `k`) of `cred_type` and keep the good
2716/// `(issuer, subject)` pairs, the same as Python's `collect_verified`.
2717///
2718/// The caller says which parties exist: `publicKeys` (a key map) or
2719/// `trustedIssuers` (a member set). With neither, nothing is collected, so a
2720/// threshold can never be met by freshly minted did:key identities.
2721fn collect(
2722    p: &Value,
2723    k: &str,
2724    keys: &KeyIn,
2725    cred_type: &str,
2726    role: Option<&str>,
2727    now: &str,
2728) -> Result<Vec<rvf::VerifiedPair>> {
2729    let members = trusted_of(p)?;
2730    collect_with(p, k, keys, cred_type, role, now, members.as_ref())
2731}
2732
2733/// `collect` with an explicit member set (used by the predicates whose own
2734/// member list doubles as the set when `trustedIssuers` is absent).
2735fn collect_with(
2736    p: &Value,
2737    k: &str,
2738    keys: &KeyIn,
2739    cred_type: &str,
2740    role: Option<&str>,
2741    now: &str,
2742    members: Option<&HashSet<String>>,
2743) -> Result<Vec<rvf::VerifiedPair>> {
2744    let creds = garr(p, k)?;
2745    let now_ns = rvf::require_now(now)?;
2746    Ok(rvf::collect_verified(
2747        &creds,
2748        keys.keys(),
2749        cred_type,
2750        now_ns,
2751        rvf::Window::IfPresent,
2752        role,
2753        members,
2754    ))
2755}
2756
2757/// The optional `trustedIssuers` member set of a request.
2758fn trusted_of(p: &Value) -> Result<Option<HashSet<String>>> {
2759    Ok(gostrs(p, "trustedIssuers")?.map(|v| v.into_iter().collect()))
2760}
2761
2762// accumulator ---------------------------------------------------------------
2763
2764fn tree_of(p: &Value) -> Result<dtn::SparseMerkleTree> {
2765    let mut t = dtn::SparseMerkleTree::new();
2766    for id in gstrs(p, "revokedIds")? {
2767        t.revoke(&id);
2768    }
2769    Ok(t)
2770}
2771
2772/// `{revokedIds}` -> `{root}`: the sparse-Merkle revocation root (multibase).
2773pub fn sparse_merkle_root(params_json: &str, _host_now: &str) -> Result<String> {
2774    let p = parse(params_json)?;
2775    Ok(json!({"root": tree_of(&p)?.root_multibase()}).to_string())
2776}
2777
2778/// `{revokedIds, credentialId}` -> the compressed non-revocation proof.
2779pub fn build_non_revocation_proof(params_json: &str, _host_now: &str) -> Result<String> {
2780    let p = parse(params_json)?;
2781    Ok(tree_of(&p)?
2782        .non_revocation_proof(&rs(&p, "credentialId")?)
2783        .to_string())
2784}
2785
2786/// `{credentialId, proof, root}` (root as multibase) -> bool.
2787pub fn verify_non_revocation_proof(params_json: &str, _host_now: &str) -> Result<String> {
2788    let p = parse(params_json)?;
2789    let raw = r::unmb64(&rs(&p, "root")?)
2790        .map_err(|_| CoreError::Json("root must be a multibase 32-byte value".into()))?;
2791    let root: [u8; 32] = raw
2792        .as_slice()
2793        .try_into()
2794        .map_err(|_| CoreError::Json("root must be a multibase 32-byte value".into()))?;
2795    Ok(b(dtn::verify_non_revocation_proof(
2796        &rs(&p, "credentialId")?,
2797        &rval(&p, "proof")?,
2798        &root,
2799    )))
2800}
2801
2802// dtn_revocation ------------------------------------------------------------
2803
2804/// `{authorityDid, revokedIds, epoch, created?}`.
2805pub fn build_revocation_accumulator_root(
2806    seed: &[u8],
2807    params_json: &str,
2808    host_now: &str,
2809) -> Result<String> {
2810    let p = parse(params_json)?;
2811    Ok(dtn::build_revocation_accumulator_root(
2812        seed,
2813        &rs(&p, "authorityDid")?,
2814        &tree_of(&p)?,
2815        ri(&p, "epoch")?,
2816        &created_or(&p, host_now)?,
2817    )?
2818    .to_string())
2819}
2820
2821/// `{authorityDid, targetCredentialId, subjectDid, deadlineEpoch, created?}`.
2822pub fn build_conditional_revocation(
2823    seed: &[u8],
2824    params_json: &str,
2825    host_now: &str,
2826) -> Result<String> {
2827    let p = parse(params_json)?;
2828    Ok(dtn::build_conditional_revocation(
2829        seed,
2830        &rs(&p, "authorityDid")?,
2831        &rs(&p, "targetCredentialId")?,
2832        &rs(&p, "subjectDid")?,
2833        ri(&p, "deadlineEpoch")?,
2834        &created_or(&p, host_now)?,
2835    )?
2836    .to_string())
2837}
2838
2839/// `{authorityDid, targetCredentialId, subjectDid, renewalEpoch, created?}`.
2840pub fn build_revocation_renewal(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
2841    let p = parse(params_json)?;
2842    Ok(dtn::build_revocation_renewal(
2843        seed,
2844        &rs(&p, "authorityDid")?,
2845        &rs(&p, "targetCredentialId")?,
2846        &rs(&p, "subjectDid")?,
2847        ri(&p, "renewalEpoch")?,
2848        &created_or(&p, host_now)?,
2849    )?
2850    .to_string())
2851}
2852
2853/// `{credential, publicKeys?, now?}` -> subject or null.
2854pub fn verify_conditional_revocation(params_json: &str, host_now: &str) -> Result<String> {
2855    let p = parse(params_json)?;
2856    let k = KeyIn::from(&p, "publicKeys")?;
2857    Ok(subj(dtn::verify_conditional_revocation(
2858        &rval(&p, "credential")?,
2859        k.keys(),
2860        &now_or(&p, host_now)?,
2861    )?))
2862}
2863
2864/// `{subject, currentEpoch, authorityDid?, renewals?, publicKeys?, now?}` ->
2865/// bool. Renewals are signed `ConditionalRevocationRenewal` credentials,
2866/// verified here.
2867pub fn conditional_revocation_active(params_json: &str, host_now: &str) -> Result<String> {
2868    let p = parse(params_json)?;
2869    let k = KeyIn::from(&p, "publicKeys")?;
2870    let now = now_or(&p, host_now)?;
2871    let renewals = collect(&p, "renewals", &k, dtn::REVOCATION_RENEWAL_TYPE, None, &now)?;
2872    Ok(b(dtn::conditional_revocation_active(
2873        &rval(&p, "subject")?,
2874        ri(&p, "currentEpoch")?,
2875        gos(&p, "authorityDid")?.as_deref(),
2876        &renewals,
2877    )?))
2878}
2879
2880/// `{credentialId, proof, signedRoot, publicKeys?, verifierEpoch, tier?,
2881/// maxEpochGap?, seenEpoch?, now?}` -> `{ok, epoch}`.
2882pub fn verify_non_revocation(params_json: &str, host_now: &str) -> Result<String> {
2883    let p = parse(params_json)?;
2884    let k = KeyIn::from(&p, "publicKeys")?;
2885    let (ok, epoch) = dtn::verify_non_revocation(
2886        &rs(&p, "credentialId")?,
2887        &rval(&p, "proof")?,
2888        &rval(&p, "signedRoot")?,
2889        k.keys(),
2890        ri(&p, "verifierEpoch")?,
2891        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
2892        oi(&p, "maxEpochGap")?,
2893        oi(&p, "seenEpoch")?,
2894        &now_or(&p, host_now)?,
2895    )?;
2896    Ok(json!({"ok": ok, "epoch": epoch}).to_string())
2897}
2898
2899// bundle ----------------------------------------------------------------------
2900
2901/// `{originatorDid, bundleId, payloadHash, intent, epoch, nonce, validWindow?:
2902/// [from, until], created?}`.
2903pub fn bind_credential_to_bundle(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
2904    let p = parse(params_json)?;
2905    let window = match goarr(&p, "validWindow")? {
2906        None => None,
2907        Some(a) => {
2908            let s = strs_of(&a, "validWindow")?;
2909            if s.len() != 2 {
2910                return Err(wrong_type("validWindow", "two time strings"));
2911            }
2912            Some(s)
2913        }
2914    };
2915    Ok(dtn::bind_credential_to_bundle(
2916        seed,
2917        &rs(&p, "originatorDid")?,
2918        &rs(&p, "bundleId")?,
2919        &rs(&p, "payloadHash")?,
2920        &rval(&p, "intent")?,
2921        ri(&p, "epoch")?,
2922        &rs(&p, "nonce")?,
2923        window.as_ref().map(|w| (w[0].as_str(), w[1].as_str())),
2924        &created_or(&p, host_now)?,
2925    )?
2926    .to_string())
2927}
2928
2929/// `{relayDid, bundleId, previousCustodian?, epoch, created?}`.
2930pub fn build_custody_transfer(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
2931    let p = parse(params_json)?;
2932    Ok(dtn::build_custody_transfer(
2933        seed,
2934        &rs(&p, "relayDid")?,
2935        &rs(&p, "bundleId")?,
2936        gos(&p, "previousCustodian")?.as_deref(),
2937        ri(&p, "epoch")?,
2938        &created_or(&p, host_now)?,
2939    )?
2940    .to_string())
2941}
2942
2943/// `{credential, publicKeys?, payloadHash, verifierEpoch, expectedNonce?,
2944/// seenNonces?, tier? (routine), maxEpochGap?, seenEpoch?, now?}` -> subject or null.
2945pub fn verify_bundle_trust(params_json: &str, host_now: &str) -> Result<String> {
2946    let p = parse(params_json)?;
2947    let k = KeyIn::from(&p, "publicKeys")?;
2948    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_ROUTINE, true)?;
2949    Ok(subj(dtn::verify_bundle_trust(
2950        &rval(&p, "credential")?,
2951        k.keys(),
2952        &rs(&p, "payloadHash")?,
2953        &mut rp.replay(),
2954        &now_or(&p, host_now)?,
2955    )?))
2956}
2957
2958/// `{credential, publicKeys?, now?}` -> subject or null.
2959pub fn verify_custody_transfer(params_json: &str, host_now: &str) -> Result<String> {
2960    let p = parse(params_json)?;
2961    let k = KeyIn::from(&p, "publicKeys")?;
2962    Ok(subj(dtn::verify_custody_transfer(
2963        &rval(&p, "credential")?,
2964        k.keys(),
2965        &now_or(&p, host_now)?,
2966    )?))
2967}
2968
2969/// `{transfers, publicKeys?, bundleId, originator, now?}` -> bool.
2970pub fn custody_chain_ok(params_json: &str, host_now: &str) -> Result<String> {
2971    let p = parse(params_json)?;
2972    let k = KeyIn::from(&p, "publicKeys")?;
2973    let now = now_or(&p, host_now)?;
2974    let pairs = collect(&p, "transfers", &k, dtn::CUSTODY_TRANSFER_TYPE, None, &now)?;
2975    Ok(b(dtn::custody_chain_ok(
2976        &pairs,
2977        &rs(&p, "bundleId")?,
2978        &rs(&p, "originator")?,
2979    )))
2980}
2981
2982// edge_trust ----------------------------------------------------------------
2983
2984/// `{signerDid, sourceClass, sinceDisciplineS, uncertaintyS, epoch, nonce, created?}`.
2985pub fn build_time_quality_attestation(
2986    seed: &[u8],
2987    params_json: &str,
2988    host_now: &str,
2989) -> Result<String> {
2990    let p = parse(params_json)?;
2991    Ok(dtn::build_time_quality_attestation(
2992        seed,
2993        &rs(&p, "signerDid")?,
2994        &rs(&p, "sourceClass")?,
2995        rf(&p, "sinceDisciplineS")?,
2996        rf(&p, "uncertaintyS")?,
2997        ri(&p, "epoch")?,
2998        &rs(&p, "nonce")?,
2999        &created_or(&p, host_now)?,
3000    )?
3001    .to_string())
3002}
3003
3004/// `{credential, publicKeys?, verifierEpoch, expectedNonce?, seenNonces?, tier?,
3005/// maxEpochGap?, seenEpoch?, expectedSubject?, now?}` -> subject or null.
3006pub fn verify_time_quality_attestation(params_json: &str, host_now: &str) -> Result<String> {
3007    let p = parse(params_json)?;
3008    let k = KeyIn::from(&p, "publicKeys")?;
3009    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_CRITICAL, true)?;
3010    Ok(subj(dtn::verify_time_quality_attestation(
3011        &rval(&p, "credential")?,
3012        k.keys(),
3013        &mut rp.replay(),
3014        gos(&p, "expectedSubject")?.as_deref(),
3015        &now_or(&p, host_now)?,
3016    )?))
3017}
3018
3019/// `{subject, tier?, budgetOverride?}` -> bool.
3020pub fn time_quality_permits(params_json: &str, _host_now: &str) -> Result<String> {
3021    let p = parse(params_json)?;
3022    Ok(b(dtn::time_quality_permits(
3023        &rval(&p, "subject")?,
3024        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
3025        gof(&p, "budgetOverride")?,
3026    )))
3027}
3028
3029/// `{steps}` -> the problem string, or null when the schedule is well formed.
3030pub fn schedule_problem(params_json: &str, _host_now: &str) -> Result<String> {
3031    let p = parse(params_json)?;
3032    Ok(match dtn::schedule_problem(present(&p, "steps")) {
3033        Some(s) => json!(s).to_string(),
3034        None => "null".into(),
3035    })
3036}
3037
3038/// `{authorityDid, subjectDid, steps, created?}`.
3039pub fn build_autonomy_schedule(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3040    let p = parse(params_json)?;
3041    Ok(dtn::build_autonomy_schedule(
3042        seed,
3043        &rs(&p, "authorityDid")?,
3044        &rs(&p, "subjectDid")?,
3045        &rval(&p, "steps")?,
3046        &created_or(&p, host_now)?,
3047    )?
3048    .to_string())
3049}
3050
3051/// `{credential, publicKeys?, expectedSubject, now?}` -> subject or null.
3052pub fn verify_autonomy_schedule(params_json: &str, host_now: &str) -> Result<String> {
3053    let p = parse(params_json)?;
3054    let k = KeyIn::from(&p, "publicKeys")?;
3055    Ok(subj(dtn::verify_autonomy_schedule(
3056        &rval(&p, "credential")?,
3057        k.keys(),
3058        &rs(&p, "expectedSubject")?,
3059        &now_or(&p, host_now)?,
3060    )?))
3061}
3062
3063/// `{subject, stalenessEpochs, holdLast?}` -> the envelope in force, or null.
3064pub fn select_envelope(params_json: &str, _host_now: &str) -> Result<String> {
3065    let p = parse(params_json)?;
3066    Ok(dtn::select_envelope(
3067        &rval(&p, "subject")?,
3068        ri(&p, "stalenessEpochs")?,
3069        gbool(&p, "holdLast")?,
3070    )
3071    .unwrap_or(Value::Null)
3072    .to_string())
3073}
3074
3075/// `{subject, stalenessEpochs, action, holdLast?}` -> bool.
3076pub fn autonomy_permits(params_json: &str, _host_now: &str) -> Result<String> {
3077    let p = parse(params_json)?;
3078    Ok(b(dtn::autonomy_permits(
3079        &rval(&p, "subject")?,
3080        ri(&p, "stalenessEpochs")?,
3081        &action_from(&rval(&p, "action")?)?,
3082        gbool(&p, "holdLast")?,
3083    )))
3084}
3085
3086/// `{attestation}` -> the attestation's chain hash.
3087pub fn integrity_attestation_hash(params_json: &str, _host_now: &str) -> Result<String> {
3088    let p = parse(params_json)?;
3089    Ok(json!(dtn::integrity_attestation_hash(&rval(&p, "attestation")?)).to_string())
3090}
3091
3092/// `{signerDid, cumulativeRisk, epoch, nonce, metrics?, prevHash?, created?}`.
3093pub fn build_integrity_risk_attestation(
3094    seed: &[u8],
3095    params_json: &str,
3096    host_now: &str,
3097) -> Result<String> {
3098    let p = parse(params_json)?;
3099    Ok(dtn::build_integrity_risk_attestation(
3100        seed,
3101        &rs(&p, "signerDid")?,
3102        rf(&p, "cumulativeRisk")?,
3103        ri(&p, "epoch")?,
3104        &rs(&p, "nonce")?,
3105        present(&p, "metrics"),
3106        gos(&p, "prevHash")?.as_deref(),
3107        &created_or(&p, host_now)?,
3108    )?
3109    .to_string())
3110}
3111
3112/// Same request as [`verify_time_quality_attestation`] -> subject or null.
3113pub fn verify_integrity_risk_attestation(params_json: &str, host_now: &str) -> Result<String> {
3114    let p = parse(params_json)?;
3115    let k = KeyIn::from(&p, "publicKeys")?;
3116    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_CRITICAL, true)?;
3117    Ok(subj(dtn::verify_integrity_risk_attestation(
3118        &rval(&p, "credential")?,
3119        k.keys(),
3120        &mut rp.replay(),
3121        gos(&p, "expectedSubject")?.as_deref(),
3122        &now_or(&p, host_now)?,
3123    )?))
3124}
3125
3126/// `{attestations, publicKeys?, verifierEpoch, expectedSubject, tier?,
3127/// maxEpochGap?, now?}` -> the newest subject, or null.
3128pub fn verify_integrity_chain(params_json: &str, host_now: &str) -> Result<String> {
3129    let p = parse(params_json)?;
3130    let k = KeyIn::from(&p, "publicKeys")?;
3131    // priorHead / seenEpoch: what the verifier remembers of this node (the
3132    // hash and epoch of the last link it accepted).
3133    Ok(subj(dtn::verify_integrity_chain_since(
3134        &garr(&p, "attestations")?,
3135        k.keys(),
3136        ri(&p, "verifierEpoch")?,
3137        &rs(&p, "expectedSubject")?,
3138        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
3139        oi(&p, "maxEpochGap")?,
3140        gos(&p, "priorHead")?.as_deref(),
3141        oi(&p, "seenEpoch")?,
3142        &now_or(&p, host_now)?,
3143    )?))
3144}
3145
3146/// `{cumulativeRisk, narrowThreshold? (0.3), suspectThreshold? (0.7)}` -> level.
3147pub fn integrity_authority_level(params_json: &str, _host_now: &str) -> Result<String> {
3148    let p = parse(params_json)?;
3149    let risk = match present(&p, "cumulativeRisk") {
3150        Some(x) if x.is_number() => x.as_f64().unwrap_or(f64::NAN),
3151        Some(_) => return Err(wrong_type("cumulativeRisk", "a number")),
3152        None => return Err(CoreError::Json("cumulativeRisk is required".into())),
3153    };
3154    Ok(json!(dtn::integrity_authority_level(
3155        risk,
3156        gof(&p, "narrowThreshold")?.unwrap_or(0.3),
3157        gof(&p, "suspectThreshold")?.unwrap_or(0.7),
3158    ))
3159    .to_string())
3160}
3161
3162// freshness -----------------------------------------------------------------
3163
3164/// `{relayDid, subjectDid, epoch, nonce, created?}`.
3165pub fn build_freshness_token(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3166    let p = parse(params_json)?;
3167    Ok(dtn::build_freshness_token(
3168        seed,
3169        &rs(&p, "relayDid")?,
3170        &rs(&p, "subjectDid")?,
3171        ri(&p, "epoch")?,
3172        &rs(&p, "nonce")?,
3173        &created_or(&p, host_now)?,
3174    )?
3175    .to_string())
3176}
3177
3178/// `{credential, publicKeys?, expectedSubject, verifierEpoch, expectedNonce?,
3179/// seenNonces?, tier?, maxEpochGap?, seenEpoch?, now?}` -> subject or null.
3180pub fn verify_freshness_token(params_json: &str, host_now: &str) -> Result<String> {
3181    let p = parse(params_json)?;
3182    let k = KeyIn::from(&p, "publicKeys")?;
3183    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_CRITICAL, true)?;
3184    Ok(subj(dtn::verify_freshness_token(
3185        &rval(&p, "credential")?,
3186        k.keys(),
3187        &rs(&p, "expectedSubject")?,
3188        &mut rp.replay(),
3189        &now_or(&p, host_now)?,
3190    )?))
3191}
3192
3193/// `{tier, maxEpochGap?}` -> the epoch gap allowed.
3194pub fn epoch_gap_budget(params_json: &str, _host_now: &str) -> Result<String> {
3195    let p = parse(params_json)?;
3196    Ok(json!(dtn::epoch_gap_budget(
3197        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
3198        oi(&p, "maxEpochGap")?,
3199    )?)
3200    .to_string())
3201}
3202
3203/// `{epoch, verifierEpoch, tier?, maxEpochGap?, seenEpoch?}` -> bool.
3204pub fn epoch_acceptable(params_json: &str, _host_now: &str) -> Result<String> {
3205    let p = parse(params_json)?;
3206    Ok(b(dtn::epoch_acceptable(
3207        p.get("epoch"),
3208        ri(&p, "verifierEpoch")?,
3209        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
3210        oi(&p, "maxEpochGap")?,
3211        oi(&p, "seenEpoch")?,
3212    )?))
3213}
3214
3215/// `{nonce, expectedNonce?, seenNonces?}` -> bool.
3216pub fn nonce_acceptable(params_json: &str, _host_now: &str) -> Result<String> {
3217    let p = parse(params_json)?;
3218    let seen = gostrs(&p, "seenNonces")?.map(|v| v.into_iter().collect::<HashSet<_>>());
3219    Ok(b(dtn::nonce_acceptable(
3220        p.get("nonce"),
3221        gos(&p, "expectedNonce")?.as_deref(),
3222        seen.as_ref(),
3223    )?))
3224}
3225
3226/// `{elapsedEpochs, halfLifeEpochs, form? ("exponential")}` -> weight in [0, 1].
3227pub fn decay_weight(params_json: &str, _host_now: &str) -> Result<String> {
3228    let p = parse(params_json)?;
3229    Ok(json!(dtn::decay_weight(
3230        ri(&p, "elapsedEpochs")?,
3231        rf(&p, "halfLifeEpochs")?,
3232        &gos(&p, "form")?.unwrap_or_else(|| "exponential".into()),
3233    )?)
3234    .to_string())
3235}
3236
3237/// `{elapsedEpochs, halfLifeEpochs, tier?, form?, thresholdOverride?}` -> bool.
3238pub fn decay_permits(params_json: &str, _host_now: &str) -> Result<String> {
3239    let p = parse(params_json)?;
3240    Ok(b(dtn::decay_permits(
3241        ri(&p, "elapsedEpochs")?,
3242        rf(&p, "halfLifeEpochs")?,
3243        &gos(&p, "tier")?.unwrap_or_else(|| dtn::CONSEQUENCE_CRITICAL.into()),
3244        &gos(&p, "form")?.unwrap_or_else(|| "exponential".into()),
3245        gof(&p, "thresholdOverride")?,
3246    )?))
3247}
3248
3249// geoscope ------------------------------------------------------------------
3250
3251/// `{region, position}` -> bool.
3252pub fn region_contains(params_json: &str, _host_now: &str) -> Result<String> {
3253    let p = parse(params_json)?;
3254    Ok(b(dtn::region_contains(
3255        &rval(&p, "region")?,
3256        rv3(&p, "position")?,
3257    )?))
3258}
3259
3260/// `{parent, child}` -> bool (the child region lies inside the parent).
3261pub fn region_attenuates(params_json: &str, _host_now: &str) -> Result<String> {
3262    let p = parse(params_json)?;
3263    Ok(b(dtn::region_attenuates(
3264        &rval(&p, "parent")?,
3265        &rval(&p, "child")?,
3266    )?))
3267}
3268
3269/// `{issuerDid, holderDid, grantId, region, physicalScope?, parentGrantId?, created?}`.
3270pub fn build_geoscoped_grant(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3271    let p = parse(params_json)?;
3272    Ok(dtn::build_geoscoped_grant(
3273        seed,
3274        &rs(&p, "issuerDid")?,
3275        &rs(&p, "holderDid")?,
3276        &rs(&p, "grantId")?,
3277        &rval(&p, "region")?,
3278        present(&p, "physicalScope"),
3279        gos(&p, "parentGrantId")?.as_deref(),
3280        &created_or(&p, host_now)?,
3281    )?
3282    .to_string())
3283}
3284
3285/// `{credential, publicKeys?, parentRegion?, now?}` -> subject or null.
3286pub fn verify_geoscoped_grant(params_json: &str, host_now: &str) -> Result<String> {
3287    let p = parse(params_json)?;
3288    let k = KeyIn::from(&p, "publicKeys")?;
3289    Ok(subj(dtn::verify_geoscoped_grant(
3290        &rval(&p, "credential")?,
3291        k.keys(),
3292        present(&p, "parentRegion"),
3293        &now_or(&p, host_now)?,
3294    )?))
3295}
3296
3297/// `{subject, position}` -> bool.
3298pub fn geoscope_permits(params_json: &str, _host_now: &str) -> Result<String> {
3299    let p = parse(params_json)?;
3300    Ok(b(dtn::geoscope_permits(
3301        &rval(&p, "subject")?,
3302        rv3(&p, "position")?,
3303    )))
3304}
3305
3306// localization --------------------------------------------------------------
3307
3308/// `{observerDid, targetDid, observerPosition, measuredRangeM, nonce, epoch, created?}`.
3309pub fn build_range_observation(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3310    let p = parse(params_json)?;
3311    Ok(dtn::build_range_observation(
3312        seed,
3313        &rs(&p, "observerDid")?,
3314        &rs(&p, "targetDid")?,
3315        rv3(&p, "observerPosition")?,
3316        rf(&p, "measuredRangeM")?,
3317        &rs(&p, "nonce")?,
3318        ri(&p, "epoch")?,
3319        &created_or(&p, host_now)?,
3320    )?
3321    .to_string())
3322}
3323
3324/// `{credential, publicKeys?, now?}` -> subject or null.
3325pub fn verify_range_observation(params_json: &str, host_now: &str) -> Result<String> {
3326    let p = parse(params_json)?;
3327    let k = KeyIn::from(&p, "publicKeys")?;
3328    Ok(subj(dtn::verify_range_observation(
3329        &rval(&p, "credential")?,
3330        k.keys(),
3331        &now_or(&p, host_now)?,
3332    )?))
3333}
3334
3335fn range_pairs(p: &Value, host_now: &str) -> Result<Vec<rvf::VerifiedPair>> {
3336    let k = KeyIn::from(p, "publicKeys")?;
3337    let now = now_or(p, host_now)?;
3338    collect(
3339        p,
3340        "observations",
3341        &k,
3342        dtn::RANGE_OBSERVATION_TYPE,
3343        Some("observer"),
3344        &now,
3345    )
3346}
3347
3348/// `{observations, publicKeys?, claimedPosition, toleranceM, targetDid?, now?}`
3349/// -> the number of distinct consistent observers.
3350pub fn count_consistent(params_json: &str, host_now: &str) -> Result<String> {
3351    let p = parse(params_json)?;
3352    let pairs = range_pairs(&p, host_now)?;
3353    Ok(json!(dtn::count_consistent(
3354        &pairs,
3355        rv3(&p, "claimedPosition")?,
3356        rf(&p, "toleranceM")?,
3357        gos(&p, "targetDid")?.as_deref(),
3358    )?)
3359    .to_string())
3360}
3361
3362/// [`count_consistent`] plus `threshold` -> bool.
3363pub fn location_confirmed(params_json: &str, host_now: &str) -> Result<String> {
3364    let p = parse(params_json)?;
3365    let pairs = range_pairs(&p, host_now)?;
3366    let threshold = usize::try_from(ri(&p, "threshold")?)
3367        .map_err(|_| wrong_type("threshold", "a non-negative whole number"))?;
3368    Ok(b(dtn::location_confirmed(
3369        &pairs,
3370        rv3(&p, "claimedPosition")?,
3371        rf(&p, "toleranceM")?,
3372        threshold,
3373        gos(&p, "targetDid")?.as_deref(),
3374    )?))
3375}
3376
3377/// `{combinerDid, targetDid, position, observerDids, epoch, created?}`.
3378pub fn build_proof_of_location(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3379    let p = parse(params_json)?;
3380    Ok(dtn::build_proof_of_location(
3381        seed,
3382        &rs(&p, "combinerDid")?,
3383        &rs(&p, "targetDid")?,
3384        rv3(&p, "position")?,
3385        &gstrs(&p, "observerDids")?,
3386        ri(&p, "epoch")?,
3387        &created_or(&p, host_now)?,
3388    )?
3389    .to_string())
3390}
3391
3392/// `{priorPosition, claimedPosition, elapsedSeconds, envelope, priorVelocity?,
3393/// toleranceM? (0)}` -> bool.
3394pub fn kinematically_reachable(params_json: &str, _host_now: &str) -> Result<String> {
3395    let p = parse(params_json)?;
3396    Ok(b(dtn::kinematically_reachable(
3397        rv3(&p, "priorPosition")?,
3398        rv3(&p, "claimedPosition")?,
3399        rf(&p, "elapsedSeconds")?,
3400        &rval(&p, "envelope")?,
3401        ov3(&p, "priorVelocity")?,
3402        gof(&p, "toleranceM")?.unwrap_or(0.0),
3403    )?))
3404}
3405
3406/// `{pointing, peerDirection, beamwidthRad}` -> bool.
3407pub fn within_beam(params_json: &str, _host_now: &str) -> Result<String> {
3408    let p = parse(params_json)?;
3409    #[cfg(not(feature = "std"))]
3410    {
3411        let _ = p;
3412        Err(CoreError::Json(
3413            "within_beam needs the std feature of vouch-core (transcendental math)".into(),
3414        ))
3415    }
3416    #[cfg(feature = "std")]
3417    Ok(b(dtn::within_beam(
3418        rv3(&p, "pointing")?,
3419        rv3(&p, "peerDirection")?,
3420        rf(&p, "beamwidthRad")?,
3421    )))
3422}
3423
3424/// `{issuerDid, peerDid, nonce, pointing, beamwidthRad, created?}`.
3425pub fn build_beam_presence(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3426    let p = parse(params_json)?;
3427    Ok(dtn::build_beam_presence(
3428        seed,
3429        &rs(&p, "issuerDid")?,
3430        &rs(&p, "peerDid")?,
3431        &rs(&p, "nonce")?,
3432        rv3(&p, "pointing")?,
3433        rf(&p, "beamwidthRad")?,
3434        &created_or(&p, host_now)?,
3435    )?
3436    .to_string())
3437}
3438
3439/// `{credential, publicKeys?, peerDirection, maxBeamwidthRad?, expectedNonce?,
3440/// seenNonces?, now?}` -> subject or null.
3441pub fn verify_beam_presence(params_json: &str, host_now: &str) -> Result<String> {
3442    let p = parse(params_json)?;
3443    let k = KeyIn::from(&p, "publicKeys")?;
3444    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_CRITICAL, false)?;
3445    Ok(subj(dtn::verify_beam_presence(
3446        &rval(&p, "credential")?,
3447        k.keys(),
3448        rv3(&p, "peerDirection")?,
3449        gof(&p, "maxBeamwidthRad")?.unwrap_or(dtn::DEFAULT_MAX_BEAMWIDTH_RAD),
3450        &mut rp.replay(),
3451        &now_or(&p, host_now)?,
3452    )?))
3453}
3454
3455// orbital -------------------------------------------------------------------
3456
3457/// `{r0, v0, dt, mu?}` -> `{position, velocity}`.
3458pub fn propagate_two_body(params_json: &str, _host_now: &str) -> Result<String> {
3459    let p = parse(params_json)?;
3460    let (r, v) = dtn::propagate_two_body(
3461        rv3(&p, "r0")?,
3462        rv3(&p, "v0")?,
3463        rf(&p, "dt")?,
3464        gof(&p, "mu")?.unwrap_or(dtn::MU_EARTH),
3465    )?;
3466    Ok(json!({"position": r, "velocity": v}).to_string())
3467}
3468
3469/// `{priorPosition, priorVelocity, claimedPosition, elapsedSeconds, mu?,
3470/// maxDeltaVMps? (0), toleranceM? (0)}` -> bool.
3471pub fn reachable_two_body(params_json: &str, _host_now: &str) -> Result<String> {
3472    let p = parse(params_json)?;
3473    Ok(b(dtn::reachable_two_body(
3474        rv3(&p, "priorPosition")?,
3475        rv3(&p, "priorVelocity")?,
3476        rv3(&p, "claimedPosition")?,
3477        rf(&p, "elapsedSeconds")?,
3478        gof(&p, "mu")?.unwrap_or(dtn::MU_EARTH),
3479        gof(&p, "maxDeltaVMps")?.unwrap_or(0.0),
3480        gof(&p, "toleranceM")?.unwrap_or(0.0),
3481    )?))
3482}
3483
3484// perception_consensus ------------------------------------------------------
3485
3486/// `{signerDid, sceneNonce, feature, value, epoch, created?}`.
3487pub fn build_perception_claim(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3488    let p = parse(params_json)?;
3489    Ok(dtn::build_perception_claim(
3490        seed,
3491        &rs(&p, "signerDid")?,
3492        &rs(&p, "sceneNonce")?,
3493        &rs(&p, "feature")?,
3494        &rval(&p, "value")?,
3495        ri(&p, "epoch")?,
3496        &created_or(&p, host_now)?,
3497    )?
3498    .to_string())
3499}
3500
3501/// `{credential, publicKeys?, now?}` -> subject or null.
3502pub fn verify_perception_claim(params_json: &str, host_now: &str) -> Result<String> {
3503    let p = parse(params_json)?;
3504    let k = KeyIn::from(&p, "publicKeys")?;
3505    Ok(subj(dtn::verify_perception_claim(
3506        &rval(&p, "credential")?,
3507        k.keys(),
3508        &now_or(&p, host_now)?,
3509    )?))
3510}
3511
3512/// `{claims, publicKeys?, tolerance, threshold, sceneNonce?, feature?, now?}` ->
3513/// `{corroborated, flagged}`.
3514pub fn cross_check_perception(params_json: &str, host_now: &str) -> Result<String> {
3515    let p = parse(params_json)?;
3516    let k = KeyIn::from(&p, "publicKeys")?;
3517    let now = now_or(&p, host_now)?;
3518    let pairs = collect(
3519        &p,
3520        "claims",
3521        &k,
3522        dtn::PERCEPTION_CLAIM_TYPE,
3523        Some("id"),
3524        &now,
3525    )?;
3526    let threshold = usize::try_from(ri(&p, "threshold")?)
3527        .map_err(|_| wrong_type("threshold", "a non-negative whole number"))?;
3528    let (c, f) = dtn::cross_check_perception(
3529        &pairs,
3530        rf(&p, "tolerance")?,
3531        threshold,
3532        gos(&p, "sceneNonce")?.as_deref(),
3533        gos(&p, "feature")?.as_deref(),
3534    )?;
3535    Ok(json!({"corroborated": c, "flagged": f}).to_string())
3536}
3537
3538/// `{signerDid, peerDid, outcome, epoch, created?}`.
3539pub fn build_interaction_attestation(
3540    seed: &[u8],
3541    params_json: &str,
3542    host_now: &str,
3543) -> Result<String> {
3544    let p = parse(params_json)?;
3545    Ok(dtn::build_interaction_attestation(
3546        seed,
3547        &rs(&p, "signerDid")?,
3548        &rs(&p, "peerDid")?,
3549        &rs(&p, "outcome")?,
3550        ri(&p, "epoch")?,
3551        &created_or(&p, host_now)?,
3552    )?
3553    .to_string())
3554}
3555
3556/// `{credential, publicKeys?, now?}` -> subject or null.
3557pub fn verify_interaction_attestation(params_json: &str, host_now: &str) -> Result<String> {
3558    let p = parse(params_json)?;
3559    let k = KeyIn::from(&p, "publicKeys")?;
3560    Ok(subj(dtn::verify_interaction_attestation(
3561        &rval(&p, "credential")?,
3562        k.keys(),
3563        &now_or(&p, host_now)?,
3564    )?))
3565}
3566
3567/// `{attestations, publicKeys?, nodeDid, currentEpoch, halfLifeEpochs,
3568/// memberDids, positiveOutcomes? (ok, success, authenticated), now?}` -> standing.
3569pub fn node_standing(params_json: &str, host_now: &str) -> Result<String> {
3570    let p = parse(params_json)?;
3571    #[cfg(not(feature = "std"))]
3572    {
3573        let _ = (p, host_now);
3574        Err(CoreError::Json(
3575            "node_standing needs the std feature of vouch-core (transcendental math)".into(),
3576        ))
3577    }
3578    #[cfg(feature = "std")]
3579    node_standing_std(p, host_now)
3580}
3581
3582#[cfg(feature = "std")]
3583fn node_standing_std(p: Value, host_now: &str) -> Result<String> {
3584    let k = KeyIn::from(&p, "publicKeys")?;
3585    let now = now_or(&p, host_now)?;
3586    // Only a trustedIssuers set names issuers that verify without a key in
3587    // publicKeys. With none, nothing is trusted on the member list's say-so
3588    // (fail closed): an unkeyed did:key member counts for nobody.
3589    let trusted = trusted_of(&p)?;
3590    let pairs = collect_with(
3591        &p,
3592        "attestations",
3593        &k,
3594        dtn::INTERACTION_ATTESTATION_TYPE,
3595        None,
3596        &now,
3597        trusted.as_ref(),
3598    )?;
3599    let outcomes = gostrs(&p, "positiveOutcomes")?
3600        .unwrap_or_else(|| vec!["ok".into(), "success".into(), "authenticated".into()]);
3601    let refs: Vec<&str> = outcomes.iter().map(String::as_str).collect();
3602    Ok(json!(dtn::node_standing(
3603        &pairs,
3604        &rs(&p, "nodeDid")?,
3605        ri(&p, "currentEpoch")?,
3606        rf(&p, "halfLifeEpochs")?,
3607        &str_set(&p, "memberDids")?,
3608        &refs,
3609    ))
3610    .to_string())
3611}
3612
3613// presence ------------------------------------------------------------------
3614
3615/// `{a, b}` -> metres.
3616pub fn expected_range_m(params_json: &str, _host_now: &str) -> Result<String> {
3617    let p = parse(params_json)?;
3618    Ok(json!(dtn::expected_range_m(rv3(&p, "a")?, rv3(&p, "b")?)).to_string())
3619}
3620
3621/// `{verifier, peer, peerVel}` -> m/s.
3622pub fn radial_velocity_mps(params_json: &str, _host_now: &str) -> Result<String> {
3623    let p = parse(params_json)?;
3624    Ok(json!(dtn::radial_velocity_mps(
3625        rv3(&p, "verifier")?,
3626        rv3(&p, "peer")?,
3627        rv3(&p, "peerVel")?,
3628    ))
3629    .to_string())
3630}
3631
3632/// `{verifier, peer, peerVel, carrierHz, propagationMps? (c)}` -> Hz.
3633pub fn expected_doppler_hz(params_json: &str, _host_now: &str) -> Result<String> {
3634    let p = parse(params_json)?;
3635    Ok(json!(dtn::expected_doppler_hz(
3636        rv3(&p, "verifier")?,
3637        rv3(&p, "peer")?,
3638        rv3(&p, "peerVel")?,
3639        rf(&p, "carrierHz")?,
3640        gof(&p, "propagationMps")?.unwrap_or(dtn::SPEED_OF_LIGHT_MPS),
3641    ))
3642    .to_string())
3643}
3644
3645/// `{verifierPosition, claimedPeerPosition, measuredRangeM, toleranceM}` ->
3646/// `{ok, residualM}` (residualM is |measured - predicted|).
3647pub fn check_presence(params_json: &str, _host_now: &str) -> Result<String> {
3648    let p = parse(params_json)?;
3649    let tolerance = rf(&p, "toleranceM")?;
3650    if tolerance < 0.0 {
3651        return Err(CoreError::Json("toleranceM must be non-negative".into()));
3652    }
3653    let a = rv3(&p, "verifierPosition")?;
3654    let peer = rv3(&p, "claimedPeerPosition")?;
3655    let measured = rf(&p, "measuredRangeM")?;
3656    let residual = (measured - dtn::expected_range_m(a, peer)).abs();
3657    Ok(json!({
3658        "ok": dtn::check_presence(a, peer, measured, tolerance),
3659        "residualM": residual,
3660    })
3661    .to_string())
3662}
3663
3664/// `{issuerDid, peerDid, nonce, claimedPosition, measuredRangeM, toleranceM,
3665/// claimedVelocity?, created?}`.
3666pub fn build_presence_attestation(
3667    seed: &[u8],
3668    params_json: &str,
3669    host_now: &str,
3670) -> Result<String> {
3671    let p = parse(params_json)?;
3672    Ok(dtn::build_presence_attestation(
3673        seed,
3674        &rs(&p, "issuerDid")?,
3675        &rs(&p, "peerDid")?,
3676        &rs(&p, "nonce")?,
3677        rv3(&p, "claimedPosition")?,
3678        rf(&p, "measuredRangeM")?,
3679        rf(&p, "toleranceM")?,
3680        ov3(&p, "claimedVelocity")?,
3681        &created_or(&p, host_now)?,
3682    )?
3683    .to_string())
3684}
3685
3686/// `{credential, publicKeys?, verifierPosition, maxToleranceM?, expectedNonce?,
3687/// seenNonces?, now?}` -> subject or null.
3688pub fn verify_presence_attestation(params_json: &str, host_now: &str) -> Result<String> {
3689    let p = parse(params_json)?;
3690    let k = KeyIn::from(&p, "publicKeys")?;
3691    let mut rp = ReplayIn::from(&p, dtn::CONSEQUENCE_CRITICAL, false)?;
3692    Ok(subj(dtn::verify_presence_attestation(
3693        &rval(&p, "credential")?,
3694        k.keys(),
3695        rv3(&p, "verifierPosition")?,
3696        gof(&p, "maxToleranceM")?.unwrap_or(dtn::DEFAULT_MAX_TOLERANCE_M),
3697        &mut rp.replay(),
3698        &now_or(&p, host_now)?,
3699    )?))
3700}
3701
3702// provenance ----------------------------------------------------------------
3703
3704/// `{attestation}` -> its chain id.
3705pub fn provenance_attestation_id(params_json: &str, _host_now: &str) -> Result<String> {
3706    let p = parse(params_json)?;
3707    Ok(json!(r::provenance_attestation_id(&rval(&p, "attestation")?)).to_string())
3708}
3709
3710/// `{attestations, publicKeys?, robotDid, now?}` -> the newest subject, or null.
3711pub fn verify_provenance_chain(params_json: &str, host_now: &str) -> Result<String> {
3712    let p = parse(params_json)?;
3713    let k = KeyIn::from(&p, "publicKeys")?;
3714    Ok(subj(r::verify_provenance_chain(
3715        &garr(&p, "attestations")?,
3716        k.keys(),
3717        &rs(&p, "robotDid")?,
3718        &now_or(&p, host_now)?,
3719    )?))
3720}
3721
3722// quorum_trust --------------------------------------------------------------
3723
3724/// `{observerDid, targetDid, reason, evidenceRef, epoch, created?}`.
3725pub fn build_distress_attestation(
3726    seed: &[u8],
3727    params_json: &str,
3728    host_now: &str,
3729) -> Result<String> {
3730    let p = parse(params_json)?;
3731    Ok(dtn::build_distress_attestation(
3732        seed,
3733        &rs(&p, "observerDid")?,
3734        &rs(&p, "targetDid")?,
3735        &rs(&p, "reason")?,
3736        &rs(&p, "evidenceRef")?,
3737        ri(&p, "epoch")?,
3738        &created_or(&p, host_now)?,
3739    )?
3740    .to_string())
3741}
3742
3743/// `{credential, publicKeys?, now?}` -> subject or null.
3744pub fn verify_distress_attestation(params_json: &str, host_now: &str) -> Result<String> {
3745    let p = parse(params_json)?;
3746    let k = KeyIn::from(&p, "publicKeys")?;
3747    Ok(subj(dtn::verify_distress_attestation(
3748        &rval(&p, "credential")?,
3749        k.keys(),
3750        &now_or(&p, host_now)?,
3751    )?))
3752}
3753
3754/// `{credentials, publicKeys?, targetDid, threshold, members, window: [from,
3755/// to], dedupeByKey?, now?}` -> bool. With `dedupeByKey`, member DIDs sharing
3756/// one key count once.
3757pub fn is_quarantined(params_json: &str, host_now: &str) -> Result<String> {
3758    let p = parse(params_json)?;
3759    let k = KeyIn::from(&p, "publicKeys")?;
3760    let now = now_or(&p, host_now)?;
3761    // Only a trustedIssuers set names issuers that verify without a key in
3762    // publicKeys. With none, nothing is trusted on the member list's say-so
3763    // (fail closed): an unkeyed did:key member counts for nobody.
3764    let trusted = trusted_of(&p)?;
3765    let pairs = collect_with(
3766        &p,
3767        "credentials",
3768        &k,
3769        dtn::DISTRESS_TYPE,
3770        Some("observer"),
3771        &now,
3772        trusted.as_ref(),
3773    )?;
3774    let threshold = usize::try_from(ri(&p, "threshold")?)
3775        .map_err(|_| wrong_type("threshold", "a non-negative whole number"))?;
3776    Ok(b(dtn::is_quarantined(
3777        &pairs,
3778        &rs(&p, "targetDid")?,
3779        threshold,
3780        &str_set(&p, "members")?,
3781        epoch_pair(&p, "window")?,
3782        gbool(&p, "dedupeByKey")?.then_some(&k.map),
3783    )?))
3784}
3785
3786/// `{anchorDid, scope, change, epoch, failureDomain, created?}`.
3787pub fn build_trust_state_update(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3788    let p = parse(params_json)?;
3789    Ok(dtn::build_trust_state_update(
3790        seed,
3791        &rs(&p, "anchorDid")?,
3792        &rs(&p, "scope")?,
3793        &rval(&p, "change")?,
3794        ri(&p, "epoch")?,
3795        &rs(&p, "failureDomain")?,
3796        &created_or(&p, host_now)?,
3797    )?
3798    .to_string())
3799}
3800
3801/// `{credential, publicKeys?, now?}` -> subject or null.
3802pub fn verify_trust_state_update(params_json: &str, host_now: &str) -> Result<String> {
3803    let p = parse(params_json)?;
3804    let k = KeyIn::from(&p, "publicKeys")?;
3805    Ok(subj(dtn::verify_trust_state_update(
3806        &rval(&p, "credential")?,
3807        k.keys(),
3808        &now_or(&p, host_now)?,
3809    )?))
3810}
3811
3812/// `{updates, anchors: {did: {x (base64url key), domain}}, currentEpoch,
3813/// threshold, accepted?: [[scope, epoch]], now?}` -> `{accepted, recorded}`,
3814/// where `recorded` is the updated accepted set to keep for the next call.
3815pub fn accept_trust_state_update(params_json: &str, host_now: &str) -> Result<String> {
3816    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3817    use base64::Engine;
3818    let p = parse(params_json)?;
3819    let mut anchors = Vec::new();
3820    if let Some(obj) = present(&p, "anchors") {
3821        let obj = obj
3822            .as_object()
3823            .ok_or_else(|| wrong_type("anchors", "an object"))?;
3824        for (did, a) in obj {
3825            let x = a
3826                .get("x")
3827                .and_then(Value::as_str)
3828                .ok_or_else(|| wrong_type("anchors.x", "a base64url key"))?;
3829            let domain = a
3830                .get("domain")
3831                .and_then(Value::as_str)
3832                .ok_or_else(|| wrong_type("anchors.domain", "a string"))?;
3833            anchors.push(dtn::TrustAnchor {
3834                did: did.clone(),
3835                public_key: URL_SAFE_NO_PAD
3836                    .decode(x)
3837                    .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?,
3838                failure_domain: domain.to_string(),
3839            });
3840        }
3841    }
3842    let mut accepted: HashSet<(String, i64)> = HashSet::new();
3843    for e in garr(&p, "accepted")? {
3844        match e.as_array().map(Vec::as_slice) {
3845            Some([Value::String(s), n]) if rvf::is_strict_int(n) => {
3846                accepted.insert((s.clone(), n.as_i64().unwrap_or(0)));
3847            }
3848            _ => return Err(wrong_type("accepted", "a list of [scope, epoch] pairs")),
3849        }
3850    }
3851    let threshold = usize::try_from(ri(&p, "threshold")?)
3852        .map_err(|_| wrong_type("threshold", "a non-negative whole number"))?;
3853    let ok = dtn::accept_trust_state_update(
3854        &garr(&p, "updates")?,
3855        &anchors,
3856        ri(&p, "currentEpoch")?,
3857        threshold,
3858        Some(&mut accepted),
3859        &now_or(&p, host_now)?,
3860    )?;
3861    let mut recorded: Vec<(String, i64)> = accepted.into_iter().collect();
3862    recorded.sort();
3863    Ok(json!({"accepted": ok, "recorded": recorded}).to_string())
3864}
3865
3866/// `{authorityDid, missionCredentialId, memberDids, threshold, epochWindow:
3867/// [from, to], created?}`.
3868pub fn build_key_continuity_predelegation(
3869    seed: &[u8],
3870    params_json: &str,
3871    host_now: &str,
3872) -> Result<String> {
3873    let p = parse(params_json)?;
3874    let threshold = usize::try_from(ri(&p, "threshold")?)
3875        .map_err(|_| wrong_type("threshold", "a non-negative whole number"))?;
3876    Ok(dtn::build_key_continuity_predelegation(
3877        seed,
3878        &rs(&p, "authorityDid")?,
3879        &rs(&p, "missionCredentialId")?,
3880        &gstrs(&p, "memberDids")?,
3881        threshold,
3882        epoch_pair(&p, "epochWindow")?,
3883        &created_or(&p, host_now)?,
3884    )?
3885    .to_string())
3886}
3887
3888/// `{memberDid, reissuanceId, supersedes, epoch, created?}`.
3889pub fn build_continuity_approval(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3890    let p = parse(params_json)?;
3891    Ok(dtn::build_continuity_approval(
3892        seed,
3893        &rs(&p, "memberDid")?,
3894        &rs(&p, "reissuanceId")?,
3895        &rs(&p, "supersedes")?,
3896        ri(&p, "epoch")?,
3897        &created_or(&p, host_now)?,
3898    )?
3899    .to_string())
3900}
3901
3902/// `{predelegation, authorityKeys, reissuanceId, supersedes, approvals,
3903/// memberKeys, supersededCredential, reissuedCredential, now?}` -> bool.
3904pub fn verify_key_continuity(params_json: &str, host_now: &str) -> Result<String> {
3905    let p = parse(params_json)?;
3906    let auth = KeyIn::from(&p, "authorityKeys")?;
3907    let members = KeyIn::from(&p, "memberKeys")?;
3908    Ok(b(dtn::verify_key_continuity(
3909        &rval(&p, "predelegation")?,
3910        auth.keys(),
3911        &rs(&p, "reissuanceId")?,
3912        &rs(&p, "supersedes")?,
3913        &garr(&p, "approvals")?,
3914        &members.map,
3915        &rval(&p, "supersededCredential")?,
3916        &rval(&p, "reissuedCredential")?,
3917        &now_or(&p, host_now)?,
3918    )?))
3919}
3920
3921/// `{original, reissued}` -> bool.
3922pub fn preserves_or_narrows(params_json: &str, _host_now: &str) -> Result<String> {
3923    let p = parse(params_json)?;
3924    let authority = gos(&p, "authorityDid")?;
3925    Ok(b(dtn::preserves_or_narrows(
3926        &rval(&p, "original")?,
3927        &rval(&p, "reissued")?,
3928        authority.as_deref(),
3929    )))
3930}
3931
3932// root_identity -------------------------------------------------------------
3933
3934/// `{robotDid, hardwareKeyMultibase, attributes, validSeconds, validFrom?,
3935/// created?, credentialStatus?, credentialId, hardwareRootKeyMultibase?}`.
3936/// `validFrom` and `created` default to the host clock.
3937pub fn build_robot_identity(seed: &[u8], params_json: &str, host_now: &str) -> Result<String> {
3938    let p = parse(params_json)?;
3939    let created = created_or(&p, host_now)?;
3940    Ok(r::build_robot_identity(
3941        seed,
3942        &rs(&p, "robotDid")?,
3943        &rs(&p, "hardwareKeyMultibase")?,
3944        &rval(&p, "attributes")?,
3945        ri(&p, "validSeconds")?,
3946        &gos(&p, "validFrom")?.unwrap_or_else(|| created.clone()),
3947        &created,
3948        present(&p, "credentialStatus").cloned(),
3949        &rs(&p, "credentialId")?,
3950        gos(&p, "hardwareRootKeyMultibase")?.as_deref(),
3951    )?
3952    .to_string())
3953}
3954
3955/// `{authorityIdentity, recognizedIssuerCredential, robotHardwareCredential,
3956/// trustedRoot, robotPublicKey (base64url raw), rootCredential?, now?,
3957/// clockSkewSeconds? (30)}` -> `{ok, reason, robotDid, issuerDid, rootDid,
3958/// attributes, hardwareRooted}`.
3959pub fn verify_robot_identity_chain(params_json: &str, host_now: &str) -> Result<String> {
3960    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3961    use base64::Engine;
3962    let p = parse(params_json)?;
3963    let pk = URL_SAFE_NO_PAD
3964        .decode(rs(&p, "robotPublicKey")?)
3965        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
3966    let res = r::verify_robot_identity_chain(
3967        &rval(&p, "authorityIdentity")?,
3968        &rval(&p, "recognizedIssuerCredential")?,
3969        &rval(&p, "robotHardwareCredential")?,
3970        &rs(&p, "trustedRoot")?,
3971        &pk,
3972        present(&p, "rootCredential"),
3973        &now_or(&p, host_now)?,
3974        oi(&p, "clockSkewSeconds")?.unwrap_or(30),
3975    );
3976    Ok(json!({
3977        "ok": res.ok,
3978        "reason": res.reason,
3979        "robotDid": res.robot_did,
3980        "issuerDid": res.issuer_did,
3981        "rootDid": res.root_did,
3982        "attributes": res.attributes,
3983        "hardwareRooted": res.hardware_rooted,
3984    })
3985    .to_string())
3986}
3987
3988// black box and safety record -------------------------------------------------
3989
3990/// `{entries, head?, count?, genesisPrevHash?}` -> `{ok, reason}`: the chain
3991/// checks out and ends at the signed head and count.
3992pub fn verify_chain_against_head(params_json: &str, host_now: &str) -> Result<String> {
3993    verify_chain_against_head_with(params_json, host_now, LogLimits::DEFAULT)
3994}
3995
3996pub(crate) fn verify_chain_against_head_with(
3997    params_json: &str,
3998    _host_now: &str,
3999    limits: LogLimits,
4000) -> Result<String> {
4001    let p = parse_long_with(params_json, limits)?;
4002    let res = r::verify_chain_against_head_capped(
4003        &garr(&p, "entries")?,
4004        present(&p, "head"),
4005        present(&p, "count"),
4006        gos(&p, "genesisPrevHash")?.as_deref(),
4007        limits.max_bytes,
4008    );
4009    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
4010}
4011
4012/// `{summary}` -> `{ok, reason}`.
4013pub fn validate_safety_summary(params_json: &str, _host_now: &str) -> Result<String> {
4014    let p = parse(params_json)?;
4015    Ok(match r::validate_safety_summary(&rval(&p, "summary")?) {
4016        Ok(()) => json!({"ok": true, "reason": null}),
4017        Err(e) => json!({"ok": false, "reason": e.to_string()}),
4018    }
4019    .to_string())
4020}
4021
4022// ---- options and host helpers ---------------------------------------------
4023
4024/// An optional whole number.
4025fn oint(v: &Value, k: &str) -> Result<Option<i64>> {
4026    match present(v, k) {
4027        None => Ok(None),
4028        Some(x) => rvf::strict_int(Some(x))
4029            .map(Some)
4030            .ok_or_else(|| wrong_type(k, "a whole number")),
4031    }
4032}
4033
4034/// The optional `seq` of a one-entry log append (the number of the entry
4035/// being appended; 0 when absent).
4036fn gseq(p: &Value) -> Result<u64> {
4037    match oint(p, "seq")? {
4038        None => Ok(0),
4039        Some(n) if n >= 0 => Ok(n as u64),
4040        Some(_) => Err(wrong_type("seq", "a whole number from 0")),
4041    }
4042}
4043
4044fn opt_trusted(p: &Value, k: &str) -> Result<Option<HashSet<String>>> {
4045    Ok(gostrs(p, k)?.map(|v| v.into_iter().collect()))
4046}
4047
4048/// The key source of a params-style verifier: `publicKeys` (a {did: key}
4049/// map, base64url), else the call's `public_key` for `issuerDid` (or a bare
4050/// key for a did:key issuer), else `pinnedIssuer` (a self-attestation whose
4051/// issuer the caller names), else no key from the caller.
4052struct ParamKeys {
4053    map: Option<alloc::collections::BTreeMap<String, Vec<u8>>>,
4054    issuer: Option<String>,
4055    pinned: Option<String>,
4056}
4057impl ParamKeys {
4058    fn from(p: &Value) -> Result<Self> {
4059        let map = match present(p, "publicKeys") {
4060            Some(_) => Some(pk_map(p)?),
4061            None => None,
4062        };
4063        Ok(Self {
4064            map,
4065            issuer: gos(p, "issuerDid")?,
4066            pinned: gos(p, "pinnedIssuer")?,
4067        })
4068    }
4069    fn keys<'a>(&'a self, key: &'a [u8]) -> Keys<'a> {
4070        if let Some(m) = &self.map {
4071            return Keys::Map(m);
4072        }
4073        if !key.is_empty() {
4074            return keys_for(key, self.issuer.as_deref());
4075        }
4076        match &self.pinned {
4077            Some(d) if !d.is_empty() => Keys::Pinned(d),
4078            _ => Keys::Embedded,
4079        }
4080    }
4081}
4082
4083fn window_of(p: &Value) -> Result<rvf::Window> {
4084    Ok(match gos(p, "window")?.as_deref() {
4085        None | Some("required") => rvf::Window::Required,
4086        Some("fromRequired") => rvf::Window::FromRequired,
4087        Some("ifPresent") => rvf::Window::IfPresent,
4088        Some(_) => {
4089            return Err(wrong_type(
4090                "window",
4091                "\"required\", \"fromRequired\" or \"ifPresent\"",
4092            ))
4093        }
4094    })
4095}
4096
4097/// The shared robotics verification kernel. `{credential, expectedType?,
4098/// window? ("required" | "fromRequired" | "ifPresent"), publicKeys? |
4099/// issuerDid? | pinnedIssuer?, trustedIssuers?, clockSkewSeconds?, maxBytes?,
4100/// now?}` plus the call's `public_key` -> `{ok, issuer, subject, reason}`.
4101pub fn verify_robotics_credential(
4102    params_json: &str,
4103    public_key: &[u8],
4104    host_now: &str,
4105) -> Result<String> {
4106    let p = parse(params_json)?;
4107    let now = rvf::require_now(&now_or(&p, host_now)?)?;
4108    let pk = ParamKeys::from(&p)?;
4109    let trusted = opt_trusted(&p, "trustedIssuers")?;
4110    let mut opts = rvf::VerifyOptions::window(window_of(&p)?);
4111    opts.trusted_issuers = trusted.as_ref();
4112    if let Some(skew) = oint(&p, "clockSkewSeconds")? {
4113        if !(0..=120).contains(&skew) {
4114            return Err(CoreError::Json(
4115                "clock skew must be between 0 and 120 seconds".into(),
4116            ));
4117        }
4118        opts.clock_skew_seconds = skew;
4119    }
4120    if let Some(max) = oint(&p, "maxBytes")? {
4121        if max < 1 {
4122            return Err(wrong_type("maxBytes", "a positive whole number"));
4123        }
4124        opts.max_bytes = (max as usize).min(rvf::MAX_CREDENTIAL_BYTES);
4125    }
4126    let expected = gos(&p, "expectedType")?;
4127    Ok(match rvf::verify_robotics_credential(
4128        &field(&p, "credential"),
4129        pk.keys(public_key),
4130        expected.as_deref(),
4131        now,
4132        opts,
4133    ) {
4134        Ok(v) => json!({"ok": true, "issuer": v.issuer, "subject": v.subject, "reason": null}),
4135        Err(why) => json!({"ok": false, "issuer": null, "subject": null, "reason": why}),
4136    }
4137    .to_string())
4138}
4139
4140/// The credentials of `expectedType` that verify, as `[{issuer, subject}]`.
4141/// `{credentials, expectedType, window?, roleField?, publicKeys? |
4142/// issuerDid? | pinnedIssuer?, trustedIssuers?, now?}`.
4143pub fn collect_verified(params_json: &str, public_key: &[u8], host_now: &str) -> Result<String> {
4144    let p = parse(params_json)?;
4145    let now = rvf::require_now(&now_or(&p, host_now)?)?;
4146    let pk = ParamKeys::from(&p)?;
4147    let trusted = opt_trusted(&p, "trustedIssuers")?;
4148    let role = gos(&p, "roleField")?;
4149    let pairs = rvf::collect_verified(
4150        &garr(&p, "credentials")?,
4151        pk.keys(public_key),
4152        &gs(&p, "expectedType")?,
4153        now,
4154        window_of(&p)?,
4155        role.as_deref(),
4156        trusted.as_ref(),
4157    );
4158    Ok(Value::Array(
4159        pairs
4160            .iter()
4161            .map(|v| json!({"issuer": v.issuer(), "subject": v.subject()}))
4162            .collect(),
4163    )
4164    .to_string())
4165}
4166
4167/// A safety record with every check: `{credential, entries?, issuerDid?,
4168/// robotDid?, trustedIssuers?, publicKeys?, now?}` plus the call's key ->
4169/// the subject or `null`.
4170pub fn verify_safety_record_params(
4171    params_json: &str,
4172    public_key: &[u8],
4173    host_now: &str,
4174) -> Result<String> {
4175    let p = parse(params_json)?;
4176    let now = now_or(&p, host_now)?;
4177    let pk = ParamKeys::from(&p)?;
4178    let entries = goarr(&p, "entries")?;
4179    let robot = gos(&p, "robotDid")?;
4180    let trusted = opt_trusted(&p, "trustedIssuers")?;
4181    Ok(subj(r::verify_safety_record(
4182        &field(&p, "credential"),
4183        pk.keys(public_key),
4184        r::SafetyRecordCheck {
4185            entries: entries.as_deref(),
4186            robot_did: robot.as_deref(),
4187            trusted_issuers: trusted.as_ref(),
4188        },
4189        &now,
4190    )?))
4191}
4192
4193/// A conformance attestation with every check: `{credential, issuerDid?,
4194/// robotDid?, trustedIssuers?, publicKeys?, now?}` -> the subject or `null`.
4195pub fn verify_conformance_attestation_params(
4196    params_json: &str,
4197    public_key: &[u8],
4198    host_now: &str,
4199) -> Result<String> {
4200    let p = parse(params_json)?;
4201    let now = now_or(&p, host_now)?;
4202    let pk = ParamKeys::from(&p)?;
4203    let robot = gos(&p, "robotDid")?;
4204    let trusted = opt_trusted(&p, "trustedIssuers")?;
4205    Ok(subj(r::verify_conformance_attestation(
4206        &field(&p, "credential"),
4207        pk.keys(public_key),
4208        robot.as_deref(),
4209        trusted.as_ref(),
4210        &now,
4211    )?))
4212}
4213
4214/// A delegation lease with every check: `{credential, expectedRobot,
4215/// parentScope?, issuerDid?, trustedIssuers?, publicKeys?, now?}` -> the
4216/// subject or `null`.
4217pub fn verify_delegation_lease_params(
4218    params_json: &str,
4219    public_key: &[u8],
4220    host_now: &str,
4221) -> Result<String> {
4222    let p = parse(params_json)?;
4223    let now = now_or(&p, host_now)?;
4224    let pk = ParamKeys::from(&p)?;
4225    let trusted = opt_trusted(&p, "trustedIssuers")?;
4226    let parent = present(&p, "parentScope").cloned();
4227    Ok(subj(r::verify_delegation_lease(
4228        &field(&p, "credential"),
4229        pk.keys(public_key),
4230        &gs(&p, "expectedRobot")?,
4231        parent.as_ref(),
4232        trusted.as_ref(),
4233        &now,
4234    )?))
4235}
4236
4237/// A decommission with every check: `{credential, trustedAuthorities?,
4238/// robotDid?, issuerDid?, publicKeys?, now?}` -> the subject or `null`.
4239pub fn verify_decommission_params(
4240    params_json: &str,
4241    public_key: &[u8],
4242    host_now: &str,
4243) -> Result<String> {
4244    let p = parse(params_json)?;
4245    let now = now_or(&p, host_now)?;
4246    let pk = ParamKeys::from(&p)?;
4247    let trusted = opt_trusted(&p, "trustedAuthorities")?;
4248    let robot = gos(&p, "robotDid")?;
4249    Ok(subj(r::verify_decommission(
4250        &field(&p, "credential"),
4251        pk.keys(public_key),
4252        trusted.as_ref(),
4253        robot.as_deref(),
4254        &now,
4255    )?))
4256}
4257
4258fn body_roots(p: &Value) -> Result<Option<alloc::collections::BTreeMap<String, String>>> {
4259    match present(p, "bodyHardwareRoots") {
4260        None => Ok(None),
4261        Some(Value::Object(o)) => Ok(Some(
4262            o.iter()
4263                .map(|(k, v)| {
4264                    v.as_str()
4265                        .map(|s| (k.clone(), s.to_string()))
4266                        .ok_or_else(|| wrong_type("bodyHardwareRoots", "an object of strings"))
4267                })
4268                .collect::<Result<_>>()?,
4269        )),
4270        Some(_) => Err(wrong_type("bodyHardwareRoots", "an object")),
4271    }
4272}
4273
4274/// An embodiment with every check: `{credential, issuerDid?, pinnedIssuer?,
4275/// publicKeys?, bodyHardwareRoots?, now?}` -> the subject or `null`.
4276pub fn verify_embodiment_params(
4277    params_json: &str,
4278    public_key: &[u8],
4279    host_now: &str,
4280) -> Result<String> {
4281    let p = parse(params_json)?;
4282    let now = now_or(&p, host_now)?;
4283    let pk = ParamKeys::from(&p)?;
4284    let roots = body_roots(&p)?;
4285    Ok(subj(r::verify_embodiment(
4286        &field(&p, "credential"),
4287        pk.keys(public_key),
4288        roots.as_ref(),
4289        &now,
4290    )?))
4291}
4292
4293/// A custody handoff with every check: `{credential, issuerDid?,
4294/// pinnedIssuer?, publicKeys?, taskId?, releaserKeys? ({did: key},
4295/// base64url), requireRelease?, fromActor?, now?}` -> the subject or `null`.
4296pub fn verify_handoff_params(
4297    params_json: &str,
4298    public_key: &[u8],
4299    host_now: &str,
4300) -> Result<String> {
4301    let p = parse(params_json)?;
4302    let now = now_or(&p, host_now)?;
4303    let pk = ParamKeys::from(&p)?;
4304    let task = gos(&p, "taskId")?;
4305    let from_actor = gos(&p, "fromActor")?;
4306    let releaser = match present(&p, "releaserKeys") {
4307        Some(v) => Some(Keys::map_of(
4308            owner_keys(v)?.into_iter().map(|k| (k.did, k.public_key)),
4309        )),
4310        None => None,
4311    };
4312    Ok(subj(r::verify_handoff(
4313        &field(&p, "credential"),
4314        pk.keys(public_key),
4315        r::HandoffCheck {
4316            task_id: task.as_deref(),
4317            releaser_keys: releaser.as_ref().map(Keys::Map),
4318            require_release: gbool(&p, "requireRelease")?,
4319            from_actor: from_actor.as_deref(),
4320        },
4321        &now,
4322    )?))
4323}
4324
4325/// Verify an ACCEPT with the caller's limits: `{accept, hello,
4326/// expectedNonce?, policy?, responderDid?, clockSkewSeconds?,
4327/// maxAcceptAgeSeconds?, maxSessionSeconds?, now?}` plus the call's
4328/// `accept_public_key` -> the session or `null`.
4329pub fn verify_accept_params(
4330    params_json: &str,
4331    accept_public_key: &[u8],
4332    host_now: &str,
4333) -> Result<String> {
4334    let p = parse(params_json)?;
4335    let now = now_or(&p, host_now)?;
4336    let pol = match present(&p, "policy") {
4337        Some(v) => Some(r::TrustPolicy::new(
4338            gstrs(v, "trustedDomains")?,
4339            gbool(v, "acceptUnknown")?,
4340        )),
4341        None => None,
4342    };
4343    let responder = gos(&p, "responderDid")?;
4344    let nonce = gos(&p, "expectedNonce")?;
4345    let limits = r::HandshakeLimits {
4346        clock_skew_seconds: oint(&p, "clockSkewSeconds")?
4347            .unwrap_or(r::DEFAULT_HANDSHAKE_SKEW_SECONDS),
4348        max_age_seconds: oint(&p, "maxAcceptAgeSeconds")?
4349            .unwrap_or(r::DEFAULT_MAX_HELLO_AGE_SECONDS),
4350        max_session_seconds: oint(&p, "maxSessionSeconds")?
4351            .unwrap_or(r::DEFAULT_MAX_SESSION_SECONDS),
4352    };
4353    let session = r::verify_accept_with(
4354        &field(&p, "accept"),
4355        keys_self(accept_public_key, responder.as_deref()),
4356        &field(&p, "hello"),
4357        nonce.as_deref().filter(|n| !n.is_empty()),
4358        pol.as_ref(),
4359        limits,
4360        &now,
4361    )?;
4362    Ok(session
4363        .map(|s| session_to_json(&s))
4364        .unwrap_or(Value::Null)
4365        .to_string())
4366}
4367
4368/// `{policy: {trustedDomains, acceptUnknown}, did}` -> whether the trust
4369/// policy accepts that DID.
4370pub fn trust_policy_is_trusted(params_json: &str) -> Result<bool> {
4371    let p = parse(params_json)?;
4372    let v = field(&p, "policy");
4373    let pol = r::TrustPolicy::new(gstrs(&v, "trustedDomains")?, gbool(&v, "acceptUnknown")?);
4374    Ok(pol.is_trusted(&gs(&p, "did")?))
4375}
4376
4377/// Liveness with every option: `{credential, intervalSeconds?,
4378/// graceIntervals?, maxIntervalSeconds?, now?}` -> true or false.
4379pub fn is_live_params(params_json: &str, host_now: &str) -> Result<bool> {
4380    let p = parse(params_json)?;
4381    let now = now_or(&p, host_now)?;
4382    r::is_live_capped(
4383        &field(&p, "credential"),
4384        &now,
4385        oint(&p, "intervalSeconds")?,
4386        oint(&p, "graceIntervals")?.unwrap_or(3),
4387        oint(&p, "maxIntervalSeconds")?.unwrap_or(r::MAX_INTERVAL_SECONDS),
4388    )
4389}
4390
4391/// `{digest}` -> `{ok, reason}`: why a motion digest is malformed.
4392pub fn motion_digest_problem(params_json: &str) -> Result<String> {
4393    let p = parse(params_json)?;
4394    Ok(match r::validate_motion_digest(&field(&p, "digest")) {
4395        Ok(()) => json!({"ok": true, "reason": null}),
4396        Err(e) => json!({"ok": false, "reason": e.to_string()}),
4397    }
4398    .to_string())
4399}
4400
4401/// Append one black-box entry with an optional host nonce: `key` (32 bytes),
4402/// `nonce` (12 bytes, optional), `{seq, event, payload, timestamp,
4403/// prevHash}` -> the entry.
4404pub fn blackbox_append(key: &[u8], nonce: Option<&[u8]>, params_json: &str) -> Result<String> {
4405    let p = parse(params_json)?;
4406    let seq = match oint(&p, "seq")? {
4407        Some(n) if n >= 0 => n as u64,
4408        _ => return Err(wrong_type("seq", "a whole number from 0")),
4409    };
4410    Ok(r::blackbox_append_entry_with_nonce(
4411        key,
4412        seq,
4413        &gs(&p, "event")?,
4414        &field(&p, "payload"),
4415        &gs(&p, "timestamp")?,
4416        &gs(&p, "prevHash")?,
4417        nonce,
4418    )?
4419    .to_string())
4420}
4421
4422/// `{scope}` -> the list of reasons the physical scope is malformed.
4423pub fn scope_problems(params_json: &str) -> Result<String> {
4424    let p = parse(params_json)?;
4425    Ok(json!(r::scope_problems(&field(&p, "scope"))).to_string())
4426}
4427
4428/// `{value}` -> minutes after midnight for an "HH:MM" time, or `null`.
4429pub fn parse_hm(params_json: &str) -> Result<String> {
4430    let p = parse(params_json)?;
4431    Ok(json!(r::parse_hm(&gs(&p, "value")?)).to_string())
4432}
4433
4434/// `{forceN, speedMps, scope}` -> whether a human handover is inside the scope.
4435pub fn handover_in_envelope(params_json: &str) -> Result<bool> {
4436    let p = parse(params_json)?;
4437    Ok(crate::robotics_domain::handover_in_envelope(
4438        &field(&p, "forceN"),
4439        &field(&p, "speedMps"),
4440        &field(&p, "scope"),
4441    ))
4442}
4443
4444/// `{tier}` -> the tier's default budgets: `{tier, stalenessBudgetSeconds,
4445/// maxEpochGap, weightThreshold, timeUncertaintyBudget}`.
4446pub fn tier_defaults(params_json: &str) -> Result<String> {
4447    let p = parse(params_json)?;
4448    let tier = gs(&p, "tier")?;
4449    Ok(json!({
4450        "tier": tier,
4451        "stalenessBudgetSeconds": dtn::default_staleness_budget_seconds(&tier),
4452        "maxEpochGap": dtn::default_max_epoch_gap(&tier),
4453        "weightThreshold": dtn::default_weight_threshold(&tier),
4454        "timeUncertaintyBudget": dtn::default_time_uncertainty_budget(&tier),
4455    })
4456    .to_string())
4457}
4458
4459/// Freshness of an unsigned snapshot: `{tier, snapshot?, budgetSeconds?,
4460/// now?}` -> `{allow, tier, reason, stalenessSeconds, budgetSeconds}`. The
4461/// caller has already checked the snapshot's proof and status bit.
4462pub fn evaluate_freshness(params_json: &str, host_now: &str) -> Result<String> {
4463    let p = parse(params_json)?;
4464    let now = now_or(&p, host_now)?;
4465    let v = dtn::evaluate_freshness(
4466        &gs(&p, "tier")?,
4467        present(&p, "snapshot"),
4468        &now,
4469        oint(&p, "budgetSeconds")?,
4470    )?;
4471    Ok(json!({
4472        "allow": v.allow,
4473        "tier": v.tier,
4474        "reason": v.reason,
4475        "stalenessSeconds": v.staleness_seconds,
4476        "budgetSeconds": v.budget_seconds,
4477    })
4478    .to_string())
4479}
4480
4481/// `{statusList, publicKeys, clockSkewSeconds?, now?}` -> whether the status
4482/// list is signed by the issuer it names (see
4483/// `robotics_dtn::verify_status_list_signature`).
4484pub fn verify_status_list_signature(params_json: &str, host_now: &str) -> Result<bool> {
4485    let p = parse(params_json)?;
4486    let now = now_or(&p, host_now)?;
4487    let map = pk_map(&p)?;
4488    dtn::verify_status_list_signature(
4489        &field(&p, "statusList"),
4490        Keys::Map(&map),
4491        &now,
4492        oint(&p, "clockSkewSeconds")?.unwrap_or(0),
4493    )
4494}
4495
4496/// `{profileId}` -> the built-in conformance profile with every requirement,
4497/// or `null` for an unknown id.
4498pub fn conformance_profile(params_json: &str) -> Result<String> {
4499    let p = parse(params_json)?;
4500    Ok(r::conformance_profile_json(&gs(&p, "profileId")?).to_string())
4501}
4502
4503// ---- segmented verification -------------------------------------------------
4504
4505fn opt_state(state_json: Option<&str>) -> Result<Option<Value>> {
4506    match state_json {
4507        None => Ok(None),
4508        Some(t) => {
4509            let v = parse(t)?;
4510            Ok(if v.is_null() { None } else { Some(v) })
4511        }
4512    }
4513}
4514
4515/// Check the next segment of a hash-linked log (black box, safety ledger,
4516/// perception log). `state_json` is the state the previous segment
4517/// returned, or absent / `null` for the first segment, which starts at
4518/// `genesis_prev_hash` (the default genesis when absent). Returns `{ok,
4519/// reason, state}`: the verdict over every entry so far (the verdict the
4520/// whole-log check gives for the same entries) and the state to pass with
4521/// the next segment. A state that was changed answers `{ok: false, reason,
4522/// state: null}`.
4523pub fn verify_log_segment(
4524    entries_json: &str,
4525    state_json: Option<&str>,
4526    genesis_prev_hash: Option<&str>,
4527    state_key: Option<&[u8]>,
4528) -> Result<String> {
4529    verify_log_segment_with(
4530        entries_json,
4531        state_json,
4532        genesis_prev_hash,
4533        state_key,
4534        None,
4535        LogLimits::DEFAULT,
4536    )
4537}
4538
4539fn refused_state(reason: String) -> String {
4540    json!({"ok": false, "reason": reason, "state": null}).to_string()
4541}
4542
4543pub(crate) fn verify_log_segment_with(
4544    entries_json: &str,
4545    state_json: Option<&str>,
4546    genesis_prev_hash: Option<&str>,
4547    state_key: Option<&[u8]>,
4548    history: Option<&str>,
4549    limits: LogLimits,
4550) -> Result<String> {
4551    let key = crate::robotics_segment::key_for(state_key)?;
4552    let state = opt_state(state_json)?;
4553    let entries = parse_long_with(entries_json, limits)?;
4554    let arr = entries
4555        .as_array()
4556        .ok_or_else(|| CoreError::Json("entries must be a JSON array".into()))?;
4557    let mut progress = match &state {
4558        None => r::ChainProgress::start(genesis_prev_hash),
4559        Some(s) => match crate::robotics_segment::read_chain_state(s, &key)
4560            .and_then(|p| crate::robotics_segment::check_history(s, history).map(|()| p))
4561        {
4562            Ok(p) => p,
4563            Err(why) => return Ok(refused_state(why)),
4564        },
4565    };
4566    if state.is_some() {
4567        if let Some(g) = genesis_prev_hash {
4568            if g != progress.genesis {
4569                return Ok(refused_state(
4570                    "genesisPrevHash is not the genesis of this state".into(),
4571                ));
4572            }
4573        }
4574    }
4575    r::verify_chain_segment(&mut progress, arr, limits.max_bytes);
4576    let res = progress.result();
4577    Ok(json!({
4578        "ok": res.ok,
4579        "reason": res.reason,
4580        "state": crate::robotics_segment::chain_state_for(&progress, history, &key),
4581    })
4582    .to_string())
4583}
4584
4585/// Finish a segmented log check against a signed `head` and `count` (from
4586/// a head credential, a safety-record summary, a perception attestation):
4587/// `{ok, reason}`, the verdict `verify_chain_against_head` gives for the
4588/// whole log.
4589pub fn finish_log_segments(
4590    state_json: &str,
4591    head_json: Option<&str>,
4592    count_json: Option<&str>,
4593    state_key: Option<&[u8]>,
4594) -> Result<String> {
4595    finish_log_segments_with(
4596        state_json,
4597        head_json,
4598        count_json,
4599        state_key,
4600        None,
4601        LogLimits::DEFAULT,
4602    )
4603}
4604
4605pub(crate) fn finish_log_segments_with(
4606    state_json: &str,
4607    head_json: Option<&str>,
4608    count_json: Option<&str>,
4609    state_key: Option<&[u8]>,
4610    history: Option<&str>,
4611    _limits: LogLimits,
4612) -> Result<String> {
4613    let key = crate::robotics_segment::key_for(state_key)?;
4614    let state = parse(state_json)?;
4615    let progress = match crate::robotics_segment::read_chain_state(&state, &key)
4616        .and_then(|p| crate::robotics_segment::check_history(&state, history).map(|()| p))
4617    {
4618        Ok(p) => p,
4619        Err(why) => return Ok(json!({"ok": false, "reason": why}).to_string()),
4620    };
4621    let head = opt_obj(head_json)?;
4622    let count = opt_obj(count_json)?;
4623    let res = r::finish_chain_against_head(&progress, head.as_ref(), count.as_ref());
4624    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
4625}
4626
4627/// Finish a segmented black-box check against the robot's signed head
4628/// credential `head`: `{ok, reason}`, the verdict `verify_blackbox_head`
4629/// gives for the whole log.
4630pub fn finish_log_segments_head(
4631    state_json: &str,
4632    head_json: &str,
4633    robot_pub: &[u8],
4634    issuer_did: Option<&str>,
4635    state_key: Option<&[u8]>,
4636    now_iso: &str,
4637) -> Result<String> {
4638    finish_log_segments_head_with(
4639        state_json,
4640        head_json,
4641        robot_pub,
4642        issuer_did,
4643        state_key,
4644        None,
4645        now_iso,
4646        LogLimits::DEFAULT,
4647    )
4648}
4649
4650#[allow(clippy::too_many_arguments)]
4651pub(crate) fn finish_log_segments_head_with(
4652    state_json: &str,
4653    head_json: &str,
4654    robot_pub: &[u8],
4655    issuer_did: Option<&str>,
4656    state_key: Option<&[u8]>,
4657    history: Option<&str>,
4658    now_iso: &str,
4659    _limits: LogLimits,
4660) -> Result<String> {
4661    let key = crate::robotics_segment::key_for(state_key)?;
4662    let state = parse(state_json)?;
4663    let head = parse(head_json)?;
4664    let progress = match crate::robotics_segment::read_chain_state(&state, &key)
4665        .and_then(|p| crate::robotics_segment::check_history(&state, history).map(|()| p))
4666    {
4667        Ok(p) => p,
4668        Err(why) => return Ok(json!({"ok": false, "reason": why}).to_string()),
4669    };
4670    let res = r::finish_chain_against_head_credential(
4671        &head,
4672        keys_self(robot_pub, issuer_did),
4673        &progress,
4674        now_iso,
4675    )?;
4676    Ok(json!({"ok": res.ok, "reason": res.reason}).to_string())
4677}
4678
4679/// Check the next segment of an embodiment history for forks. The history
4680/// must be in `validFrom` order. `state_json` is the state the previous
4681/// segment returned (absent / `null` for the first). Returns `{ok,
4682/// conflict, reason, state}`: the verdict over every embodiment so far (for
4683/// a history in `validFrom` order, the `{ok, conflict}` `check_no_fork`
4684/// gives for the same list) and the state for the next segment. The state
4685/// carries `count` and `digest` (a running hash of every embodiment), so a
4686/// host can confirm it checked the whole history. Through the JSON entry,
4687/// `historyId` names the history: it is sealed into the first state and a
4688/// later segment naming another one is refused.
4689pub fn check_no_fork_segment(
4690    embodiments_json: &str,
4691    state_json: Option<&str>,
4692    state_key: Option<&[u8]>,
4693) -> Result<String> {
4694    check_no_fork_segment_with(
4695        embodiments_json,
4696        state_json,
4697        state_key,
4698        None,
4699        LogLimits::DEFAULT,
4700    )
4701}
4702
4703pub(crate) fn check_no_fork_segment_with(
4704    embodiments_json: &str,
4705    state_json: Option<&str>,
4706    state_key: Option<&[u8]>,
4707    history: Option<&str>,
4708    limits: LogLimits,
4709) -> Result<String> {
4710    use crate::robotics_segment as seg;
4711    let key = seg::key_for(state_key)?;
4712    let state = opt_state(state_json)?;
4713    let embodiments = parse_long_with(embodiments_json, limits)?;
4714    let arr = embodiments
4715        .as_array()
4716        .ok_or_else(|| CoreError::Json("embodiments must be a JSON array".into()))?;
4717    let (mut progress, digest) = match &state {
4718        None => (r::ForkProgress::start(), seg::fork_digest_start()),
4719        Some(s) => match seg::read_fork_state(s, &key)
4720            .and_then(|p| seg::check_history(s, history).map(|()| p))
4721        {
4722            Ok(p) => p,
4723            Err(why) => {
4724                return Ok(
4725                    json!({"ok": false, "conflict": null, "reason": why, "state": null})
4726                        .to_string(),
4727                )
4728            }
4729        },
4730    };
4731    let mut d = match r::unmb64(&digest) {
4732        Ok(d) if d.len() == 32 => d,
4733        _ => {
4734            return Ok(json!({
4735                "ok": false,
4736                "conflict": null,
4737                "reason": "the segment state is malformed",
4738                "state": null,
4739            })
4740            .to_string())
4741        }
4742    };
4743    for e in arr {
4744        d = seg::fork_digest_step(&d, e);
4745    }
4746    r::check_no_fork_segment(&mut progress, arr);
4747    let (ok, conflict, reason) = progress.result();
4748    Ok(json!({
4749        "ok": ok,
4750        "conflict": conflict.map(|c| json!({"bodyA": c.body_a, "bodyB": c.body_b})),
4751        "reason": reason,
4752        "state": seg::fork_state_for(&progress, &r::mb64(&d), history, &key),
4753    })
4754    .to_string())
4755}
4756
4757#[cfg(test)]
4758mod tests {
4759    use super::*;
4760
4761    const NOW: &str = "2026-06-01T00:00:00Z";
4762
4763    // A present action field of the wrong type is an error, never dropped.
4764    #[test]
4765    fn wrong_typed_action_fields_are_errors() {
4766        let scope = r#"{"maxForceN": 100, "allowedZones": ["A"], "shiftWindows": [{"start": "08:00", "end": "18:00"}]}"#;
4767        for action in [
4768            r#"{"forceN": "5000"}"#,
4769            r#"{"zone": 7}"#,
4770            r#"{"timeHm": 2300}"#,
4771            r#"{"nearHumans": "true", "speedMps": 1}"#,
4772            r#"[]"#,
4773            r#"{"forceN": 1, "extra": 2}"#,
4774        ] {
4775            assert!(
4776                check_physical_action_scope(scope, action).is_err(),
4777                "{action}"
4778            );
4779            let p = format!(r#"{{"subject": {{"physicalScope": {scope}}}, "action": {action}}}"#);
4780            assert!(lease_permits(&p, NOW).is_err(), "{action}");
4781        }
4782        // Null means "not given".
4783        let ok = check_physical_action_scope(scope, r#"{"forceN": null, "zone": "A"}"#).unwrap();
4784        assert!(ok.contains("\"ok\":true"));
4785    }
4786
4787    #[test]
4788    fn wear_level_must_be_a_number() {
4789        let scope = r#"{"maxForceN": 100}"#;
4790        for p in [
4791            format!(r#"{{"scope": {scope}}}"#),
4792            format!(r#"{{"scope": {scope}, "wearLevel": null}}"#),
4793            format!(r#"{{"scope": {scope}, "wearLevel": "0.5"}}"#),
4794            format!(r#"{{"scope": {scope}, "wearLevel": 1.5}}"#),
4795        ] {
4796            assert!(attenuate_for_wear(&p).is_err(), "{p}");
4797        }
4798        assert!(attenuate_for_wear(&format!(r#"{{"scope": {scope}, "wearLevel": 0.5}}"#)).is_ok());
4799    }
4800
4801    #[test]
4802    fn approver_set_and_threshold_must_be_well_typed() {
4803        for p in [
4804            r#"{"approvals": [], "threshold": 1, "approverSet": "did:web:a"}"#,
4805            r#"{"approvals": [], "threshold": 1, "approverSet": {"did:web:a": true}}"#,
4806            r#"{"approvals": [], "threshold": "1"}"#,
4807            r#"{"approvals": {}, "threshold": 1}"#,
4808            r#"{"approvals": [], "threshold": 1, "now": 5}"#,
4809        ] {
4810            assert!(verify_action_authorization(p, NOW).is_err(), "{p}");
4811        }
4812        assert!(verify_action_authorization(r#"{"approvals": [], "threshold": 1}"#, NOW).is_ok());
4813    }
4814
4815    // No `now` in the request uses the host clock the wrapper passes; an empty
4816    // or malformed one (in the request or from the wrapper) is an error.
4817    #[test]
4818    fn clock_comes_from_the_request_or_the_host() {
4819        let v: Value = serde_json::from_str(
4820            &std::fs::read_to_string(concat!(
4821                env!("CARGO_MANIFEST_DIR"),
4822                "/../../test-vectors/robotics/vector.json"
4823            ))
4824            .unwrap(),
4825        )
4826        .unwrap();
4827        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
4828        use base64::Engine;
4829        let key = URL_SAFE_NO_PAD
4830            .decode(v["robot_public_key_jwk"]["x"].as_str().unwrap())
4831            .unwrap();
4832        let expired = v["delegation_lease_expired_credential"].to_string();
4833        assert_eq!(
4834            verify_delegation_lease(
4835                &expired,
4836                &key,
4837                NOW,
4838                None,
4839                Some("did:web:robot.example.com"),
4840                "did:web:robot.example.com"
4841            )
4842            .unwrap(),
4843            "null"
4844        );
4845        assert_ne!(
4846            verify_delegation_lease(
4847                &expired,
4848                &key,
4849                "2026-01-01T00:30:00Z",
4850                None,
4851                Some("did:web:robot.example.com"),
4852                "did:web:robot.example.com"
4853            )
4854            .unwrap(),
4855            "null"
4856        );
4857        assert!(verify_delegation_lease(
4858            &expired,
4859            &key,
4860            "",
4861            None,
4862            Some("did:web:robot.example.com"),
4863            "did:web:robot.example.com"
4864        )
4865        .is_err());
4866        assert!(verify_delegation_lease(
4867            &expired,
4868            &key,
4869            "null",
4870            None,
4871            Some("did:web:robot.example.com"),
4872            "did:web:robot.example.com"
4873        )
4874        .is_err());
4875
4876        let grant = v["access_grant_credential"].clone();
4877        let op = URL_SAFE_NO_PAD
4878            .decode(v["access_operator_key"]["x"].as_str().unwrap())
4879            .unwrap();
4880        let operator = grant["issuer"].as_str().unwrap().to_string();
4881        let p = json!({"grant": grant, "operatorDid": operator}).to_string();
4882        assert_ne!(verify_access_grant(&p, &op, NOW).unwrap(), "null");
4883        assert!(verify_access_grant(&p, &op, "").is_err());
4884        let p = json!({"grant": grant, "operatorDid": operator, "now": ""}).to_string();
4885        assert!(verify_access_grant(&p, &op, NOW).is_err());
4886        let p = json!({"grant": grant, "operatorDid": operator, "now": "2036-01-01T00:00:00Z"})
4887            .to_string();
4888        assert_eq!(verify_access_grant(&p, &op, NOW).unwrap(), "null");
4889    }
4890
4891    #[test]
4892    fn oversized_inputs_are_refused() {
4893        let big = format!(r#"{{"pad": "{}"}}"#, "a".repeat(MAX_INPUT_BYTES));
4894        assert!(verify_robot_identity(&big, &[0u8; 32], None, None, NOW).is_err());
4895        let many = format!(
4896            r#"{{"inputFrameHashes": [{}]}}"#,
4897            vec!["\"uAAAA\""; MAX_LIST_ITEMS + 1].join(",")
4898        );
4899        let err = fusion_inputs_digest(&many).unwrap_err().to_string();
4900        assert!(err.contains("more than"), "{err}");
4901        let nested = format!(
4902            r#"{{"a": {{"b": [{}]}}}}"#,
4903            vec!["1"; MAX_LIST_ITEMS + 1].join(",")
4904        );
4905        assert!(config_hash(&nested).is_err());
4906    }
4907}