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