Skip to main content

vouch_core/
robotics_domain.rs

1//! Operating-domain (ODD) conformance and robot-to-human handover.
2//!
3//! Port of the Python reference `vouch/robotics/odd.py` and `handover.py`.
4//!
5//! An operating-domain credential, signed by the operator, certifies the zones a
6//! robot may work in, a speed cap, condition bounds (`max*` upper, `min*` lower)
7//! and the time windows it is rated for. An ODD conformance attestation, signed
8//! by the robot, reports what it observed over an interval and whether that
9//! stayed inside the domain; a verifier recomputes the verdict against the
10//! certified domain, so a robot cannot claim it stayed in domain when its own
11//! observations say otherwise.
12//!
13//! A human handover credential, signed by the robot, records the force and speed
14//! at the moment it released an object to a person and whether that stayed
15//! inside the near-human envelope; the recipient signs an acknowledgement bound
16//! to that one handover by its proof value.
17
18#[allow(unused_imports)]
19use crate::prelude::*;
20
21use serde_json::{json, Map, Value};
22
23use crate::data_integrity::{self, BuildProofOptions};
24use crate::error::{CoreError, Result};
25use crate::robotics::{parse_hm, parse_windows, parse_zones, scope_problems, valid_cap};
26use crate::robotics::{VC_CONTEXT_V2, VOUCH_CONTEXT_V1};
27use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};
28
29pub const OPERATING_DOMAIN_TYPE: &str = "OperatingDomainCredential";
30pub const ODD_CONFORMANCE_TYPE: &str = "ODDConformanceAttestation";
31pub const HUMAN_HANDOVER_TYPE: &str = "HumanHandoverCredential";
32pub const HANDOVER_ACK_TYPE: &str = "HandoverAcknowledgement";
33
34/// The outcome of [`check_in_domain`]: ok plus a reason for each problem. Each
35/// reason starts with a code (`speed_out_of_domain`, `zone_out_of_domain`,
36/// `condition_out_of_domain`, `time_out_of_domain`, `not_observed`,
37/// `observed_malformed`, `domain_malformed`, `malformed`) and a ":".
38#[derive(Debug, Clone, PartialEq)]
39pub struct OddResult {
40    pub ok: bool,
41    pub reasons: Vec<String>,
42}
43
44fn sign(
45    seed: &[u8],
46    issuer: &str,
47    cred_type: &str,
48    subject: Value,
49    valid_from: &str,
50    valid_until: Option<&str>,
51) -> Result<Value> {
52    rv::require_now(valid_from)?;
53    let mut cred = Map::new();
54    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
55    cred.insert("type".into(), json!(["VerifiableCredential", cred_type]));
56    cred.insert("issuer".into(), json!(issuer));
57    cred.insert("validFrom".into(), json!(valid_from));
58    if let Some(vu) = valid_until {
59        rv::require_now(vu)?;
60        cred.insert("validUntil".into(), json!(vu));
61    }
62    cred.insert("credentialSubject".into(), subject);
63    let opts = BuildProofOptions::new(
64        crate::verification_method::ed25519_method(issuer),
65        valid_from,
66    );
67    data_integrity::sign(&Value::Object(cred), seed, &opts)
68}
69
70/// Build a signed `OperatingDomainCredential`: the operator (`operator_did`,
71/// signing with `operator_seed`) certifies `robot_did` to operate inside
72/// `domain` (an object with any of `allowedZones`, `maxSpeedMps`, `conditions`,
73/// `timeWindows`).
74pub fn build_odd_credential(
75    operator_seed: &[u8],
76    operator_did: &str,
77    robot_did: &str,
78    domain: &Value,
79    valid_from: &str,
80    valid_until: Option<&str>,
81) -> Result<Value> {
82    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); domain);
83    if robot_did.is_empty() {
84        return Err(CoreError::Json("robot_did is required".into()));
85    }
86    if !domain.is_object() {
87        return Err(CoreError::Json("domain must be an object".into()));
88    }
89    sign(
90        operator_seed,
91        operator_did,
92        OPERATING_DOMAIN_TYPE,
93        json!({"id": robot_did, "operatingDomain": domain}),
94        valid_from,
95        valid_until,
96    )
97}
98
99/// Verify an `OperatingDomainCredential`: the proof bound to the operator as
100/// issuer, validFrom present and the window current at `now_iso`, and (when
101/// given) that it certifies `robot_did` and comes from one of
102/// `trusted_operators`. Returns the operating domain (an empty object when the
103/// subject carries none).
104pub fn verify_odd_credential(
105    credential: &Value,
106    operator_keys: Keys<'_>,
107    robot_did: Option<&str>,
108    trusted_operators: Option<&crate::collections::HashSet<String>>,
109    now_iso: &str,
110) -> Result<Option<Value>> {
111    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
112    let now = rv::require_now(now_iso)?;
113    let opts = VerifyOptions {
114        trusted_issuers: trusted_operators,
115        ..VerifyOptions::window(Window::FromRequired)
116    };
117    let v = match rv::verify_robotics_credential(
118        credential,
119        operator_keys,
120        Some(OPERATING_DOMAIN_TYPE),
121        now,
122        opts,
123    ) {
124        Ok(v) => v,
125        Err(_) => return Ok(None),
126    };
127    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
128        return Ok(None);
129    }
130    match v.subject.get("operatingDomain") {
131        None | Some(Value::Null) => Ok(Some(json!({}))),
132        Some(d @ Value::Object(_)) => Ok(Some(d.clone())),
133        _ => Ok(None),
134    }
135}
136
137fn present(v: Option<&Value>) -> Option<&Value> {
138    v.filter(|x| !x.is_null())
139}
140
141fn num_text(v: &Value) -> String {
142    match v.as_f64() {
143        Some(f) => format!("{f}"),
144        None => v.to_string(),
145    }
146}
147
148/// Check observed operating parameters against a certified domain. Every
149/// dimension the domain constrains must be observed; a malformed domain or
150/// observation value is out of domain; an empty time-window list allows no
151/// time; an absent domain dimension is unconstrained.
152/// The domain dimensions [`check_in_domain`] evaluates. Anything else is refused.
153pub const ODD_DIMENSIONS: [&str; 4] = ["maxSpeedMps", "allowedZones", "conditions", "timeWindows"];
154
155pub fn check_in_domain(domain: &Value, observed: &Value) -> OddResult {
156    crate::nesting::deep_guard!(OddResult { ok: false, reasons: vec![crate::nesting::TOO_DEEP.into()] }; domain, observed);
157    let (d, o) = match (domain.as_object(), observed.as_object()) {
158        (Some(d), Some(o)) => (d, o),
159        _ => {
160            return OddResult {
161                ok: false,
162                reasons: vec!["malformed: domain and observed must be objects".into()],
163            }
164        }
165    };
166    let mut reasons: Vec<String> = Vec::new();
167    // A dimension this checker does not know limits nothing if ignored, so it
168    // is out of domain (sorted, listed first).
169    let mut unknown: Vec<&String> = d
170        .keys()
171        .filter(|k| !ODD_DIMENSIONS.contains(&k.as_str()))
172        .collect();
173    unknown.sort();
174    for k in unknown {
175        reasons.push(format!("unknown_dimension: {k}"));
176    }
177
178    if let Some(cap) = d.get("maxSpeedMps") {
179        let val = present(o.get("maxSpeedMps"));
180        if !valid_cap(cap) {
181            reasons.push("domain_malformed: maxSpeedMps".into());
182        } else if val.is_none() {
183            reasons.push("not_observed: maxSpeedMps".into());
184        } else if !valid_cap(val.unwrap()) {
185            reasons.push("observed_malformed: maxSpeedMps".into());
186        } else if val.unwrap().as_f64() > cap.as_f64() {
187            reasons.push(format!(
188                "speed_out_of_domain: {} > {}",
189                num_text(val.unwrap()),
190                num_text(cap)
191            ));
192        }
193    }
194
195    if let Some(allowed_raw) = d.get("allowedZones") {
196        let allowed = parse_zones(allowed_raw);
197        let zones = present(o.get("zones"));
198        match (allowed, zones) {
199            (None, _) => reasons.push("domain_malformed: allowedZones".into()),
200            (Some(_), None) => reasons.push("not_observed: zones".into()),
201            (Some(allowed), Some(z)) => match parse_zones(z) {
202                None => reasons.push("observed_malformed: zones".into()),
203                Some(seen) => {
204                    let outside: Vec<&str> =
205                        seen.into_iter().filter(|x| !allowed.contains(x)).collect();
206                    if !outside.is_empty() {
207                        reasons.push(format!("zone_out_of_domain: {outside:?}"));
208                    }
209                }
210            },
211        }
212    }
213
214    if let Some(bounds) = d.get("conditions") {
215        match (
216            bounds.as_object(),
217            o.get("conditions").and_then(|s| s.as_object()),
218        ) {
219            (None, _) => reasons.push("domain_malformed: conditions".into()),
220            (Some(_), None) => reasons.push("not_observed: conditions".into()),
221            (Some(bounds), Some(seen)) => {
222                for (key, bound) in bounds {
223                    let upper = key.starts_with("max");
224                    if !upper && !key.starts_with("min") {
225                        reasons.push(format!("domain_malformed: condition {key:?}"));
226                        continue;
227                    }
228                    let b = match rv::finite_number(Some(bound)) {
229                        Some(b) => b,
230                        None => {
231                            reasons.push(format!("domain_malformed: condition {key}"));
232                            continue;
233                        }
234                    };
235                    match present(seen.get(key)) {
236                        None => reasons.push(format!("not_observed: condition {key}")),
237                        Some(val) => match rv::finite_number(Some(val)) {
238                            None => reasons.push(format!("observed_malformed: condition {key}")),
239                            Some(x) if upper && x > b => {
240                                reasons.push(format!("condition_out_of_domain: {key} {x} > {b}"))
241                            }
242                            Some(x) if !upper && x < b => {
243                                reasons.push(format!("condition_out_of_domain: {key} {x} < {b}"))
244                            }
245                            Some(_) => {}
246                        },
247                    }
248                }
249            }
250        }
251    }
252
253    if let Some(raw) = d.get("timeWindows") {
254        let windows = parse_windows(raw);
255        let t = present(o.get("timeHm"));
256        match (windows, t) {
257            (None, _) => reasons.push("domain_malformed: timeWindows".into()),
258            (Some(_), None) => reasons.push("not_observed: timeHm".into()),
259            (Some(windows), Some(t)) => match t.as_str().and_then(parse_hm) {
260                None => reasons.push("observed_malformed: timeHm".into()),
261                Some(m) => {
262                    if !windows.iter().any(|(s, e)| *s <= m && m <= *e) {
263                        reasons.push(format!(
264                            "time_out_of_domain: {}",
265                            t.as_str().unwrap_or_default()
266                        ));
267                    }
268                }
269            },
270        }
271    }
272
273    OddResult {
274        ok: reasons.is_empty(),
275        reasons,
276    }
277}
278
279/// Build a signed `ODDConformanceAttestation`: the robot reports `observed`
280/// over interval `interval_index` and the in-domain verdict computed here.
281pub fn build_odd_conformance(
282    robot_seed: &[u8],
283    robot_did: &str,
284    domain: &Value,
285    observed: &Value,
286    interval_index: i64,
287    valid_from: &str,
288    valid_until: Option<&str>,
289) -> Result<Value> {
290    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); domain, observed);
291    if robot_did.is_empty() {
292        return Err(CoreError::Json("robot_did is required".into()));
293    }
294    let result = check_in_domain(domain, observed);
295    sign(
296        robot_seed,
297        robot_did,
298        ODD_CONFORMANCE_TYPE,
299        json!({
300            "id": robot_did,
301            "intervalIndex": interval_index,
302            "observed": observed,
303            "inDomain": result.ok,
304            "reasons": result.reasons,
305        }),
306        valid_from,
307        valid_until,
308    )
309}
310
311/// Verify an `ODDConformanceAttestation`: the proof bound to the robot as
312/// issuer (who must also be `credentialSubject.id`), validFrom present and the
313/// window current, `inDomain` a boolean, and recomputing [`check_in_domain`]
314/// over the attested observations against `domain` (required: the certified
315/// domain) reproduces the attested verdict.
316pub fn verify_odd_conformance(
317    credential: &Value,
318    robot_keys: Keys<'_>,
319    domain: &Value,
320    now_iso: &str,
321) -> Result<Option<Value>> {
322    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, domain);
323    let now = rv::require_now(now_iso)?;
324    let v = match rv::verify_robotics_credential(
325        credential,
326        robot_keys,
327        Some(ODD_CONFORMANCE_TYPE),
328        now,
329        VerifyOptions::window(Window::FromRequired),
330    ) {
331        Ok(v) => v,
332        Err(_) => return Ok(None),
333    };
334    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
335        return Ok(None);
336    }
337    let claimed = match v.subject.get("inDomain") {
338        Some(Value::Bool(b)) => *b,
339        _ => return Ok(None),
340    };
341    let observed = match v.subject.get("observed") {
342        Some(o @ Value::Object(_)) => o,
343        _ => return Ok(None),
344    };
345    if !domain.is_object() || check_in_domain(domain, observed).ok != claimed {
346        return Ok(None);
347    }
348    Ok(Some(v.subject))
349}
350
351/// True when a handover's force and speed fit the near-human envelope of
352/// `scope`: the scope must be well-formed, force and speed finite and
353/// non-negative, force within `maxForceN`, and speed within the lower of
354/// `maxSpeedNearHumansMps` and `maxSpeedMps`.
355pub fn handover_in_envelope(force_n: &Value, speed_mps: &Value, scope: &Value) -> bool {
356    crate::nesting::deep_guard!(false; force_n, speed_mps, scope);
357    if !scope_problems(scope).is_empty() {
358        return false;
359    }
360    let (f, s) = match (
361        rv::finite_number(Some(force_n)),
362        rv::finite_number(Some(speed_mps)),
363    ) {
364        (Some(f), Some(s)) if f >= 0.0 && s >= 0.0 => (f, s),
365        _ => return false,
366    };
367    let cap = |k: &str| scope.get(k).and_then(|v| v.as_f64());
368    if cap("maxForceN").is_some_and(|c| f > c) {
369        return false;
370    }
371    let caps: Vec<f64> = ["maxSpeedNearHumansMps", "maxSpeedMps"]
372        .iter()
373        .filter_map(|k| cap(k))
374        .collect();
375    !caps.iter().any(|c| s > *c)
376}
377
378/// Parameters for [`build_human_handover`]. When `scope` is given the
379/// near-human envelope verdict is computed and carried as `inEnvelope`.
380#[derive(Debug, Clone)]
381pub struct BuildHumanHandover {
382    pub robot_did: String,
383    pub recipient: String,
384    pub object_id: String,
385    pub force_n: f64,
386    pub speed_mps: f64,
387    pub scope: Option<Value>,
388    pub valid_from: String,
389    pub valid_until: Option<String>,
390}
391
392/// Build a signed `HumanHandoverCredential` (issued by the robot).
393pub fn build_human_handover(robot_seed: &[u8], params: &BuildHumanHandover) -> Result<Value> {
394    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); params);
395    if params.robot_did.is_empty() || params.recipient.is_empty() || params.object_id.is_empty() {
396        return Err(CoreError::Json(
397            "robot_did, recipient, and object_id are required".into(),
398        ));
399    }
400    let mut subject = json!({
401        "id": params.robot_did,
402        "recipient": params.recipient,
403        "objectId": params.object_id,
404        "envelope": {"forceN": params.force_n, "speedMps": params.speed_mps},
405    });
406    if let Some(scope) = &params.scope {
407        subject["inEnvelope"] = json!(handover_in_envelope(
408            &json!(params.force_n),
409            &json!(params.speed_mps),
410            scope
411        ));
412    }
413    sign(
414        robot_seed,
415        &params.robot_did,
416        HUMAN_HANDOVER_TYPE,
417        subject,
418        &params.valid_from,
419        params.valid_until.as_deref(),
420    )
421}
422
423/// Verify a `HumanHandoverCredential`: the proof bound to the robot as issuer
424/// (who must also be `credentialSubject.id`), validFrom present and the window
425/// current, finite envelope numbers, and, when `scope` is given, recomputing the
426/// envelope check reproduces the attested `inEnvelope` (a credential that
427/// states no verdict must be inside).
428pub fn verify_human_handover(
429    credential: &Value,
430    robot_keys: Keys<'_>,
431    scope: Option<&Value>,
432    now_iso: &str,
433) -> Result<Option<Value>> {
434    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, scope);
435    let now = rv::require_now(now_iso)?;
436    let v = match rv::verify_robotics_credential(
437        credential,
438        robot_keys,
439        Some(HUMAN_HANDOVER_TYPE),
440        now,
441        VerifyOptions::window(Window::FromRequired),
442    ) {
443        Ok(v) => v,
444        Err(_) => return Ok(None),
445    };
446    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
447        return Ok(None);
448    }
449    let env = match v.subject.get("envelope").and_then(|e| e.as_object()) {
450        Some(e) => e,
451        None => return Ok(None),
452    };
453    let (f, s) = match (env.get("forceN"), env.get("speedMps")) {
454        (Some(f), Some(s))
455            if rv::finite_number(Some(f)).is_some() && rv::finite_number(Some(s)).is_some() =>
456        {
457            (f, s)
458        }
459        _ => return Ok(None),
460    };
461    if let Some(scope) = scope {
462        let claimed = match v.subject.get("inEnvelope") {
463            None => true,
464            Some(Value::Bool(b)) => *b,
465            _ => return Ok(None),
466        };
467        if handover_in_envelope(f, s, scope) != claimed {
468            return Ok(None);
469        }
470    }
471    Ok(Some(v.subject))
472}
473
474/// Build a signed `HandoverAcknowledgement`: the recipient confirms receiving
475/// the object of `handover`, bound to it by its proof value.
476pub fn build_handover_ack(
477    recipient_seed: &[u8],
478    recipient_did: &str,
479    handover: &Value,
480    valid_from: &str,
481) -> Result<Value> {
482    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); handover);
483    let r = handover
484        .get("proof")
485        .and_then(|p| p.get("proofValue"))
486        .and_then(|v| v.as_str())
487        .filter(|s| !s.is_empty());
488    let r = match r {
489        Some(r) if !recipient_did.is_empty() => r,
490        _ => {
491            return Err(CoreError::Json(
492                "recipient_did and a signed handover are required".into(),
493            ))
494        }
495    };
496    let object_id = handover
497        .get("credentialSubject")
498        .and_then(|s| s.get("objectId"))
499        .cloned()
500        .unwrap_or(Value::Null);
501    sign(
502        recipient_seed,
503        recipient_did,
504        HANDOVER_ACK_TYPE,
505        json!({"id": recipient_did, "handoverRef": r, "objectId": object_id}),
506        valid_from,
507        None,
508    )
509}
510
511/// Verify a `HandoverAcknowledgement`: the proof bound to the issuer, who must
512/// be its subject and the recipient `handover` names, the window current, and
513/// the acknowledgement bound to `handover` by its proof value.
514pub fn verify_handover_ack(
515    ack: &Value,
516    recipient_keys: Keys<'_>,
517    handover: &Value,
518    now_iso: &str,
519) -> Result<Option<Value>> {
520    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); ack, handover);
521    let now = rv::require_now(now_iso)?;
522    let v = match rv::verify_robotics_credential(
523        ack,
524        recipient_keys,
525        Some(HANDOVER_ACK_TYPE),
526        now,
527        VerifyOptions::window(Window::FromRequired),
528    ) {
529        Ok(v) => v,
530        Err(_) => return Ok(None),
531    };
532    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
533        return Ok(None);
534    }
535    let hs = match handover
536        .get("credentialSubject")
537        .and_then(|s| s.as_object())
538    {
539        Some(s) => s,
540        None => return Ok(None),
541    };
542    if hs.get("recipient").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
543        return Ok(None);
544    }
545    let r = handover
546        .get("proof")
547        .and_then(|p| p.as_object())
548        .and_then(|p| p.get("proofValue"))
549        .and_then(|x| x.as_str())
550        .filter(|s| !s.is_empty());
551    match r {
552        Some(r) if v.subject.get("handoverRef").and_then(|x| x.as_str()) == Some(r) => {
553            Ok(Some(v.subject))
554        }
555        _ => Ok(None),
556    }
557}
558
559// ---------------------------------------------------------------------------
560// Swarm membership and collective action (port of `vouch/robotics/swarm.py`)
561// ---------------------------------------------------------------------------
562
563pub const SWARM_MEMBERSHIP_TYPE: &str = "SwarmMembershipCredential";
564pub const COLLECTIVE_ACTION_TYPE: &str = "CollectiveActionAttestation";
565
566/// Build a signed `SwarmMembershipCredential`: the coordinator admits
567/// `robot_did` to `swarm_id`, optionally with a `role`.
568pub fn build_swarm_membership(
569    coordinator_seed: &[u8],
570    coordinator_did: &str,
571    swarm_id: &str,
572    robot_did: &str,
573    role: Option<&str>,
574    valid_from: &str,
575    valid_until: Option<&str>,
576) -> Result<Value> {
577    if swarm_id.is_empty() || robot_did.is_empty() {
578        return Err(CoreError::Json(
579            "swarm_id and robot_did are required".into(),
580        ));
581    }
582    let mut subject = json!({"id": robot_did, "swarmId": swarm_id});
583    if let Some(r) = role {
584        subject["role"] = json!(r);
585    }
586    sign(
587        coordinator_seed,
588        coordinator_did,
589        SWARM_MEMBERSHIP_TYPE,
590        subject,
591        valid_from,
592        valid_until,
593    )
594}
595
596/// Verify a `SwarmMembershipCredential` bound to the coordinator as issuer,
597/// validFrom present and the window current, a non-empty `swarmId` and `id`,
598/// and (when given) for `swarm_id` and issued by `coordinator_did`.
599pub fn verify_swarm_membership(
600    credential: &Value,
601    coordinator_keys: Keys<'_>,
602    swarm_id: Option<&str>,
603    coordinator_did: Option<&str>,
604    now_iso: &str,
605) -> Result<Option<Value>> {
606    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
607    let now = rv::require_now(now_iso)?;
608    // A named coordinator is a trusted set of one: with no key, a did:key
609    // coordinator verifies under its own key only when named here.
610    let named: Option<crate::collections::HashSet<String>> =
611        coordinator_did.map(|c| [c.to_string()].into_iter().collect());
612    let v = match rv::verify_robotics_credential(
613        credential,
614        coordinator_keys,
615        Some(SWARM_MEMBERSHIP_TYPE),
616        now,
617        VerifyOptions {
618            trusted_issuers: named.as_ref(),
619            ..VerifyOptions::window(Window::FromRequired)
620        },
621    ) {
622        Ok(v) => v,
623        Err(_) => return Ok(None),
624    };
625    let s = |k: &str| {
626        v.subject
627            .get(k)
628            .and_then(|x| x.as_str())
629            .filter(|x| !x.is_empty())
630    };
631    if s("swarmId").is_none() || s("id").is_none() {
632        return Ok(None);
633    }
634    if swarm_id.is_some_and(|w| s("swarmId") != Some(w)) {
635        return Ok(None);
636    }
637    if coordinator_did.is_some_and(|c| c != v.issuer) {
638        return Ok(None);
639    }
640    Ok(Some(v.subject))
641}
642
643/// Build a signed `CollectiveActionAttestation`: the coordinator records that
644/// `participants` took `action` together as `swarm_id`.
645pub fn build_collective_action(
646    coordinator_seed: &[u8],
647    coordinator_did: &str,
648    swarm_id: &str,
649    action: &str,
650    participants: &[String],
651    valid_from: &str,
652    valid_until: Option<&str>,
653) -> Result<Value> {
654    if swarm_id.is_empty() || action.is_empty() {
655        return Err(CoreError::Json("swarm_id and action are required".into()));
656    }
657    if participants.is_empty() {
658        return Err(CoreError::Json(
659            "participants must be a non-empty list".into(),
660        ));
661    }
662    sign(
663        coordinator_seed,
664        coordinator_did,
665        COLLECTIVE_ACTION_TYPE,
666        json!({"swarmId": swarm_id, "action": action, "participants": participants}),
667        valid_from,
668        valid_until,
669    )
670}
671
672/// Verify a `CollectiveActionAttestation` bound to the coordinator, with a
673/// swarm id and a non-empty list of participant DIDs. With `memberships`,
674/// every participant must hold a membership in the same swarm from the same
675/// coordinator that was valid at the action's validFrom. Returns
676/// `(ok, unverified participants)`.
677pub fn verify_collective_action(
678    credential: &Value,
679    coordinator_keys: Keys<'_>,
680    memberships: Option<&[Value]>,
681    now_iso: &str,
682) -> Result<(bool, Vec<String>)> {
683    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, memberships);
684    let now = rv::require_now(now_iso)?;
685    let v = match rv::verify_robotics_credential(
686        credential,
687        coordinator_keys,
688        Some(COLLECTIVE_ACTION_TYPE),
689        now,
690        VerifyOptions::window(Window::FromRequired),
691    ) {
692        Ok(v) => v,
693        Err(_) => return Ok((false, Vec::new())),
694    };
695    let swarm_id = match v.subject.get("swarmId").and_then(|x| x.as_str()) {
696        Some(w) if !w.is_empty() => w.to_string(),
697        _ => return Ok((false, Vec::new())),
698    };
699    let participants: Vec<String> = match v.subject.get("participants").and_then(|p| p.as_array()) {
700        Some(a) if !a.is_empty() && a.iter().all(|x| x.as_str().is_some_and(|s| !s.is_empty())) => {
701            a.iter().map(|x| x.as_str().unwrap().to_string()).collect()
702        }
703        _ => return Ok((false, Vec::new())),
704    };
705    let memberships = match memberships {
706        None => return Ok((true, Vec::new())),
707        Some(m) => m,
708    };
709    let action_at = match credential.get("validFrom").and_then(|x| x.as_str()) {
710        Some(t) if rv::time_ns(credential.get("validFrom")).is_some() => t.to_string(),
711        _ => return Ok((false, Vec::new())),
712    };
713    let mut covered = crate::collections::HashSet::new();
714    for m in memberships {
715        if let Some(sub) = verify_swarm_membership(
716            m,
717            coordinator_keys,
718            Some(&swarm_id),
719            Some(&v.issuer),
720            &action_at,
721        )? {
722            if let Some(id) = sub.get("id").and_then(|x| x.as_str()) {
723                covered.insert(id.to_string());
724            }
725        }
726    }
727    let unverified: Vec<String> = participants
728        .into_iter()
729        .filter(|p| !covered.contains(p))
730        .collect();
731    Ok((unverified.is_empty(), unverified))
732}
733
734// ---------------------------------------------------------------------------
735// Teleoperation control handoff (port of `vouch/robotics/teleop.py`)
736// ---------------------------------------------------------------------------
737
738pub const CONTROL_HANDOFF_TYPE: &str = "ControlHandoffCredential";
739/// Control modes an interoperable verifier accepts.
740pub const CONTROL_MODES: [&str; 3] = ["autonomous", "teleoperated", "shared"];
741
742/// Parameters for [`build_control_handoff`]: the receiving controller
743/// `to_controller` (the signer) takes control of `robot_did` under `mode`.
744#[derive(Debug, Clone)]
745pub struct BuildControlHandoff {
746    pub robot_did: String,
747    pub from_controller: String,
748    pub to_controller: String,
749    pub mode: String,
750    pub valid_from: String,
751    pub valid_until: Option<String>,
752    pub prev_handoff_id: Option<String>,
753    pub credential_id: String,
754}
755
756/// Build a signed `ControlHandoffCredential` (issued by the receiver).
757pub fn build_control_handoff(receiver_seed: &[u8], p: &BuildControlHandoff) -> Result<Value> {
758    if p.robot_did.is_empty() || p.from_controller.is_empty() || p.to_controller.is_empty() {
759        return Err(CoreError::Json(
760            "robot_did, from_controller, and to_controller are required".into(),
761        ));
762    }
763    if !CONTROL_MODES.contains(&p.mode.as_str()) {
764        return Err(CoreError::Json(format!(
765            "mode must be one of {CONTROL_MODES:?}"
766        )));
767    }
768    if p.credential_id.is_empty() {
769        return Err(CoreError::Json("credential_id is required".into()));
770    }
771    let mut subject = json!({
772        "id": p.robot_did, "fromController": p.from_controller,
773        "toController": p.to_controller, "mode": p.mode,
774    });
775    if let Some(prev) = &p.prev_handoff_id {
776        subject["prevHandoffId"] = json!(prev);
777    }
778    rv::require_now(&p.valid_from)?;
779    let mut cred = Map::new();
780    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
781    cred.insert("id".into(), json!(p.credential_id));
782    cred.insert(
783        "type".into(),
784        json!(["VerifiableCredential", CONTROL_HANDOFF_TYPE]),
785    );
786    cred.insert("issuer".into(), json!(p.to_controller));
787    cred.insert("validFrom".into(), json!(p.valid_from));
788    if let Some(vu) = &p.valid_until {
789        cred.insert("validUntil".into(), json!(vu));
790    }
791    cred.insert("credentialSubject".into(), subject);
792    let opts = BuildProofOptions::new(
793        crate::verification_method::ed25519_method(&p.to_controller),
794        &p.valid_from,
795    );
796    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
797}
798
799/// Verify a control handoff: bound to the issuer, who must be `toController`,
800/// non-empty `id` / `fromController` / `toController`, a known mode, the
801/// window current, and (when given) for `robot_did`.
802pub fn verify_control_handoff(
803    credential: &Value,
804    receiver_keys: Keys<'_>,
805    robot_did: Option<&str>,
806    now_iso: &str,
807) -> Result<Option<Value>> {
808    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
809    let now = rv::require_now(now_iso)?;
810    let v = match rv::verify_robotics_credential(
811        credential,
812        receiver_keys,
813        Some(CONTROL_HANDOFF_TYPE),
814        now,
815        VerifyOptions::window(Window::FromRequired),
816    ) {
817        Ok(v) => v,
818        Err(_) => return Ok(None),
819    };
820    let s = |k: &str| {
821        v.subject
822            .get(k)
823            .and_then(|x| x.as_str())
824            .filter(|x| !x.is_empty())
825    };
826    if s("id").is_none()
827        || s("fromController").is_none()
828        || s("toController") != Some(v.issuer.as_str())
829    {
830        return Ok(None);
831    }
832    if !s("mode").is_some_and(|m| CONTROL_MODES.contains(&m)) {
833        return Ok(None);
834    }
835    if robot_did.is_some_and(|r| s("id") != Some(r)) {
836        return Ok(None);
837    }
838    Ok(Some(v.subject))
839}
840
841/// Verify an ordered list of control handoffs for `robot_did`: each verifies
842/// under its receiver's key, toController matches the next fromController,
843/// each later link names the previous `id` as `prevHandoffId`, links are in
844/// time order, the first fromController is `origin_controller`, and each
845/// earlier link was still valid when the next began (the last at `now_iso`).
846/// Returns `(ok, current_controller)`. `origin_controller` is required: with no
847/// known first controller, anyone could sign a first link taking control from
848/// themselves.
849pub fn verify_control_chain(
850    handoffs: &[Value],
851    keys: Keys<'_>,
852    robot_did: &str,
853    origin_controller: Option<&str>,
854    now_iso: &str,
855) -> Result<(bool, Option<String>)> {
856    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); handoffs);
857    rv::require_now(now_iso)?;
858    if robot_did.is_empty() || origin_controller.is_none_or(str::is_empty) {
859        return Ok((false, None));
860    }
861    let mut expected: Option<String> = origin_controller.map(String::from);
862    let mut current: Option<String> = origin_controller.map(String::from);
863    let mut prev_id: Option<String> = None;
864    let mut prev_time: Option<i128> = None;
865    for (i, h) in handoffs.iter().enumerate() {
866        let at = match handoffs.get(i + 1) {
867            Some(n) => match n.get("validFrom").and_then(|x| x.as_str()) {
868                Some(t) if rv::time_ns(n.get("validFrom")).is_some() => t.to_string(),
869                _ => return Ok((false, None)),
870            },
871            None => now_iso.to_string(),
872        };
873        let sub = match verify_control_handoff(h, keys, Some(robot_did), &at)? {
874            Some(s) => s,
875            None => return Ok((false, None)),
876        };
877        if let Some(e) = &expected {
878            if sub.get("fromController").and_then(|x| x.as_str()) != Some(e.as_str()) {
879                return Ok((false, None));
880            }
881        }
882        match rv::time_ns(h.get("validFrom")) {
883            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
884            _ => return Ok((false, None)),
885        }
886        if i > 0 {
887            match &prev_id {
888                Some(p) if sub.get("prevHandoffId").and_then(|x| x.as_str()) == Some(p) => {}
889                _ => return Ok((false, None)),
890            }
891        }
892        prev_id = h
893            .get("id")
894            .and_then(|x| x.as_str())
895            .filter(|x| !x.is_empty())
896            .map(String::from);
897        current = sub
898            .get("toController")
899            .and_then(|x| x.as_str())
900            .map(String::from);
901        expected = current.clone();
902    }
903    Ok((true, current))
904}
905
906/// The controller in charge at protocol time `at`: the toController of the
907/// most recent handoff at or before `at` (handoffs in chain order).
908pub fn controller_at(handoffs: &[Value], at: &str) -> Option<String> {
909    crate::nesting::deep_guard!(None; handoffs);
910    let when = crate::time::parse_protocol_time_ns(at).ok()?;
911    let mut holder = None;
912    for h in handoffs {
913        if rv::time_ns(h.get("validFrom")).is_some_and(|t| t <= when) {
914            // A malformed link (no subject object, a non-string controller)
915            // names nobody and leaves the holder as it was.
916            if let Some(to) = h
917                .get("credentialSubject")
918                .and_then(|s| s.get("toController"))
919                .and_then(|x| x.as_str())
920            {
921                holder = Some(to.to_string());
922            }
923        }
924    }
925    holder
926}
927
928/// Confirm the control timeline is continuous and single-held: each later
929/// handoff's fromController is the previous toController. Returns `(ok,
930/// seams)` where each seam is `{expected, found}`.
931pub fn check_control_continuity(handoffs: &[Value]) -> (bool, Vec<Value>) {
932    crate::nesting::deep_guard!((false, Vec::new()); handoffs);
933    let mut seams = Vec::new();
934    let mut prev_to: Option<String> = None;
935    for h in handoffs {
936        // A link with no subject object makes the timeline unaccountable.
937        let sub = match h.get("credentialSubject").and_then(|s| s.as_object()) {
938            Some(s) => s,
939            None => return (false, seams),
940        };
941        let frm = sub.get("fromController").and_then(|x| x.as_str());
942        if let Some(p) = &prev_to {
943            if frm != Some(p.as_str()) {
944                seams.push(json!({"expected": p, "found": frm.unwrap_or_default()}));
945            }
946        }
947        prev_to = sub
948            .get("toController")
949            .and_then(|x| x.as_str())
950            .map(String::from);
951    }
952    (seams.is_empty(), seams)
953}
954
955// What the no_std depth guard checks in the JSON these types carry.
956crate::nesting::nested_fields!(BuildHumanHandover; scope);
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961    use crate::keys::Ed25519KeyPair;
962    use crate::robotics_verify::test_keys::TNOW;
963    use alloc::collections::BTreeMap;
964
965    const T0: &str = "2026-01-01T00:00:00Z";
966
967    fn party(b: u8, did: &str) -> (Vec<u8>, BTreeMap<String, Vec<u8>>) {
968        let seed = vec![b; 32];
969        let kp = Ed25519KeyPair::from_seed_slice(&seed).unwrap();
970        (
971            seed,
972            BTreeMap::from([(did.to_string(), kp.public_key().to_vec())]),
973        )
974    }
975
976    #[test]
977    fn odd_round_trip_and_recomputed_verdict() {
978        let (op, okeys) = party(1, "did:web:op.example.com");
979        let (rb, rkeys) = party(2, "did:web:robot.example.com");
980        let domain = json!({"maxSpeedMps": 1.0, "allowedZones": ["a"]});
981        let cred = build_odd_credential(
982            &op,
983            "did:web:op.example.com",
984            "did:web:robot.example.com",
985            &domain,
986            T0,
987            None,
988        )
989        .unwrap();
990        let got = verify_odd_credential(
991            &cred,
992            Keys::Map(&okeys),
993            Some("did:web:robot.example.com"),
994            None,
995            TNOW,
996        )
997        .unwrap();
998        assert_eq!(got, Some(domain.clone()));
999        let observed = json!({"maxSpeedMps": 2.0, "zones": ["a"]});
1000        let att = build_odd_conformance(
1001            &rb,
1002            "did:web:robot.example.com",
1003            &domain,
1004            &observed,
1005            1,
1006            T0,
1007            None,
1008        )
1009        .unwrap();
1010        assert_eq!(att["credentialSubject"]["inDomain"], json!(false));
1011        assert!(
1012            verify_odd_conformance(&att, Keys::Map(&rkeys), &domain, TNOW)
1013                .unwrap()
1014                .is_some()
1015        );
1016        let looser = json!({"maxSpeedMps": 5.0, "allowedZones": ["a"]});
1017        assert!(
1018            verify_odd_conformance(&att, Keys::Map(&rkeys), &looser, TNOW)
1019                .unwrap()
1020                .is_none()
1021        );
1022    }
1023
1024    #[test]
1025    fn handover_round_trip_and_ack_binding() {
1026        let (rb, rkeys) = party(3, "did:web:robot.example.com");
1027        let (pp, pkeys) = party(4, "did:web:person.example.com");
1028        let scope = json!({"maxForceN": 20.0, "maxSpeedNearHumansMps": 0.25});
1029        let p = BuildHumanHandover {
1030            robot_did: "did:web:robot.example.com".into(),
1031            recipient: "did:web:person.example.com".into(),
1032            object_id: "cup".into(),
1033            force_n: 5.0,
1034            speed_mps: 0.2,
1035            scope: Some(scope.clone()),
1036            valid_from: T0.into(),
1037            valid_until: None,
1038        };
1039        let ho = build_human_handover(&rb, &p).unwrap();
1040        assert_eq!(ho["credentialSubject"]["inEnvelope"], json!(true));
1041        assert!(
1042            verify_human_handover(&ho, Keys::Map(&rkeys), Some(&scope), TNOW)
1043                .unwrap()
1044                .is_some()
1045        );
1046        let fast = build_human_handover(
1047            &rb,
1048            &BuildHumanHandover {
1049                speed_mps: 0.5,
1050                ..p.clone()
1051            },
1052        )
1053        .unwrap();
1054        assert_eq!(fast["credentialSubject"]["inEnvelope"], json!(false));
1055        let ack = build_handover_ack(&pp, "did:web:person.example.com", &ho, T0).unwrap();
1056        assert!(verify_handover_ack(&ack, Keys::Map(&pkeys), &ho, TNOW)
1057            .unwrap()
1058            .is_some());
1059        assert!(verify_handover_ack(&ack, Keys::Map(&pkeys), &fast, TNOW)
1060            .unwrap()
1061            .is_none());
1062        assert!(!handover_in_envelope(&json!(f64::NAN), &json!(0.1), &scope));
1063    }
1064}