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