vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Operating-domain (ODD) conformance and robot-to-human handover.
//!
//! Port of the Python reference `vouch/robotics/odd.py` and `handover.py`.
//!
//! An operating-domain credential, signed by the operator, certifies the zones a
//! robot may work in, a speed cap, condition bounds (`max*` upper, `min*` lower)
//! and the time windows it is rated for. An ODD conformance attestation, signed
//! by the robot, reports what it observed over an interval and whether that
//! stayed inside the domain; a verifier recomputes the verdict against the
//! certified domain, so a robot cannot claim it stayed in domain when its own
//! observations say otherwise.
//!
//! A human handover credential, signed by the robot, records the force and speed
//! at the moment it released an object to a person and whether that stayed
//! inside the near-human envelope; the recipient signs an acknowledgement bound
//! to that one handover by its proof value.

use serde_json::{json, Map, Value};

use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::robotics::{parse_hm, parse_windows, parse_zones, scope_problems, valid_cap};
use crate::robotics::{VC_CONTEXT_V2, VOUCH_CONTEXT_V1};
use crate::robotics_verify::{self as rv, Keys, VerifyOptions, Window};

pub const OPERATING_DOMAIN_TYPE: &str = "OperatingDomainCredential";
pub const ODD_CONFORMANCE_TYPE: &str = "ODDConformanceAttestation";
pub const HUMAN_HANDOVER_TYPE: &str = "HumanHandoverCredential";
pub const HANDOVER_ACK_TYPE: &str = "HandoverAcknowledgement";

/// The outcome of [`check_in_domain`]: ok plus a reason for each problem. Each
/// reason starts with a code (`speed_out_of_domain`, `zone_out_of_domain`,
/// `condition_out_of_domain`, `time_out_of_domain`, `not_observed`,
/// `observed_malformed`, `domain_malformed`, `malformed`) and a ":".
#[derive(Debug, Clone, PartialEq)]
pub struct OddResult {
    pub ok: bool,
    pub reasons: Vec<String>,
}

fn sign(
    seed: &[u8],
    issuer: &str,
    cred_type: &str,
    subject: Value,
    valid_from: &str,
    valid_until: Option<&str>,
) -> Result<Value> {
    rv::require_now(valid_from)?;
    let mut cred = Map::new();
    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
    cred.insert("type".into(), json!(["VerifiableCredential", cred_type]));
    cred.insert("issuer".into(), json!(issuer));
    cred.insert("validFrom".into(), json!(valid_from));
    if let Some(vu) = valid_until {
        rv::require_now(vu)?;
        cred.insert("validUntil".into(), json!(vu));
    }
    cred.insert("credentialSubject".into(), subject);
    let opts = BuildProofOptions::new(format!("{issuer}#key-1"), valid_from);
    data_integrity::sign(&Value::Object(cred), seed, &opts)
}

/// Build a signed `OperatingDomainCredential`: the operator (`operator_did`,
/// signing with `operator_seed`) certifies `robot_did` to operate inside
/// `domain` (an object with any of `allowedZones`, `maxSpeedMps`, `conditions`,
/// `timeWindows`).
pub fn build_odd_credential(
    operator_seed: &[u8],
    operator_did: &str,
    robot_did: &str,
    domain: &Value,
    valid_from: &str,
    valid_until: Option<&str>,
) -> Result<Value> {
    if robot_did.is_empty() {
        return Err(CoreError::Json("robot_did is required".into()));
    }
    if !domain.is_object() {
        return Err(CoreError::Json("domain must be an object".into()));
    }
    sign(
        operator_seed,
        operator_did,
        OPERATING_DOMAIN_TYPE,
        json!({"id": robot_did, "operatingDomain": domain}),
        valid_from,
        valid_until,
    )
}

/// Verify an `OperatingDomainCredential`: the proof bound to the operator as
/// issuer, validFrom present and the window current at `now_iso`, and (when
/// given) that it certifies `robot_did` and comes from one of
/// `trusted_operators`. Returns the operating domain (an empty object when the
/// subject carries none).
pub fn verify_odd_credential(
    credential: &Value,
    operator_keys: Keys<'_>,
    robot_did: Option<&str>,
    trusted_operators: Option<&std::collections::HashSet<String>>,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    let opts = VerifyOptions {
        trusted_issuers: trusted_operators,
        ..VerifyOptions::window(Window::FromRequired)
    };
    let v = match rv::verify_robotics_credential(
        credential,
        operator_keys,
        Some(OPERATING_DOMAIN_TYPE),
        now,
        opts,
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if robot_did.is_some_and(|r| v.subject.get("id").and_then(|x| x.as_str()) != Some(r)) {
        return Ok(None);
    }
    match v.subject.get("operatingDomain") {
        None | Some(Value::Null) => Ok(Some(json!({}))),
        Some(d @ Value::Object(_)) => Ok(Some(d.clone())),
        _ => Ok(None),
    }
}

fn present(v: Option<&Value>) -> Option<&Value> {
    v.filter(|x| !x.is_null())
}

fn num_text(v: &Value) -> String {
    match v.as_f64() {
        Some(f) => format!("{f}"),
        None => v.to_string(),
    }
}

/// Check observed operating parameters against a certified domain. Every
/// dimension the domain constrains must be observed; a malformed domain or
/// observation value is out of domain; an empty time-window list allows no
/// time; an absent domain dimension is unconstrained.
/// The domain dimensions [`check_in_domain`] evaluates. Anything else is refused.
pub const ODD_DIMENSIONS: [&str; 4] = ["maxSpeedMps", "allowedZones", "conditions", "timeWindows"];

pub fn check_in_domain(domain: &Value, observed: &Value) -> OddResult {
    let (d, o) = match (domain.as_object(), observed.as_object()) {
        (Some(d), Some(o)) => (d, o),
        _ => {
            return OddResult {
                ok: false,
                reasons: vec!["malformed: domain and observed must be objects".into()],
            }
        }
    };
    let mut reasons: Vec<String> = Vec::new();
    // A dimension this checker does not know limits nothing if ignored, so it
    // is out of domain (sorted, listed first).
    let mut unknown: Vec<&String> = d
        .keys()
        .filter(|k| !ODD_DIMENSIONS.contains(&k.as_str()))
        .collect();
    unknown.sort();
    for k in unknown {
        reasons.push(format!("unknown_dimension: {k}"));
    }

    if let Some(cap) = d.get("maxSpeedMps") {
        let val = present(o.get("maxSpeedMps"));
        if !valid_cap(cap) {
            reasons.push("domain_malformed: maxSpeedMps".into());
        } else if val.is_none() {
            reasons.push("not_observed: maxSpeedMps".into());
        } else if !valid_cap(val.unwrap()) {
            reasons.push("observed_malformed: maxSpeedMps".into());
        } else if val.unwrap().as_f64() > cap.as_f64() {
            reasons.push(format!(
                "speed_out_of_domain: {} > {}",
                num_text(val.unwrap()),
                num_text(cap)
            ));
        }
    }

    if let Some(allowed_raw) = d.get("allowedZones") {
        let allowed = parse_zones(allowed_raw);
        let zones = present(o.get("zones"));
        match (allowed, zones) {
            (None, _) => reasons.push("domain_malformed: allowedZones".into()),
            (Some(_), None) => reasons.push("not_observed: zones".into()),
            (Some(allowed), Some(z)) => match parse_zones(z) {
                None => reasons.push("observed_malformed: zones".into()),
                Some(seen) => {
                    let outside: Vec<&str> =
                        seen.into_iter().filter(|x| !allowed.contains(x)).collect();
                    if !outside.is_empty() {
                        reasons.push(format!("zone_out_of_domain: {outside:?}"));
                    }
                }
            },
        }
    }

    if let Some(bounds) = d.get("conditions") {
        match (
            bounds.as_object(),
            o.get("conditions").and_then(|s| s.as_object()),
        ) {
            (None, _) => reasons.push("domain_malformed: conditions".into()),
            (Some(_), None) => reasons.push("not_observed: conditions".into()),
            (Some(bounds), Some(seen)) => {
                for (key, bound) in bounds {
                    let upper = key.starts_with("max");
                    if !upper && !key.starts_with("min") {
                        reasons.push(format!("domain_malformed: condition {key:?}"));
                        continue;
                    }
                    let b = match rv::finite_number(Some(bound)) {
                        Some(b) => b,
                        None => {
                            reasons.push(format!("domain_malformed: condition {key}"));
                            continue;
                        }
                    };
                    match present(seen.get(key)) {
                        None => reasons.push(format!("not_observed: condition {key}")),
                        Some(val) => match rv::finite_number(Some(val)) {
                            None => reasons.push(format!("observed_malformed: condition {key}")),
                            Some(x) if upper && x > b => {
                                reasons.push(format!("condition_out_of_domain: {key} {x} > {b}"))
                            }
                            Some(x) if !upper && x < b => {
                                reasons.push(format!("condition_out_of_domain: {key} {x} < {b}"))
                            }
                            Some(_) => {}
                        },
                    }
                }
            }
        }
    }

    if let Some(raw) = d.get("timeWindows") {
        let windows = parse_windows(raw);
        let t = present(o.get("timeHm"));
        match (windows, t) {
            (None, _) => reasons.push("domain_malformed: timeWindows".into()),
            (Some(_), None) => reasons.push("not_observed: timeHm".into()),
            (Some(windows), Some(t)) => match t.as_str().and_then(parse_hm) {
                None => reasons.push("observed_malformed: timeHm".into()),
                Some(m) => {
                    if !windows.iter().any(|(s, e)| *s <= m && m <= *e) {
                        reasons.push(format!(
                            "time_out_of_domain: {}",
                            t.as_str().unwrap_or_default()
                        ));
                    }
                }
            },
        }
    }

    OddResult {
        ok: reasons.is_empty(),
        reasons,
    }
}

/// Build a signed `ODDConformanceAttestation`: the robot reports `observed`
/// over interval `interval_index` and the in-domain verdict computed here.
pub fn build_odd_conformance(
    robot_seed: &[u8],
    robot_did: &str,
    domain: &Value,
    observed: &Value,
    interval_index: i64,
    valid_from: &str,
    valid_until: Option<&str>,
) -> Result<Value> {
    if robot_did.is_empty() {
        return Err(CoreError::Json("robot_did is required".into()));
    }
    let result = check_in_domain(domain, observed);
    sign(
        robot_seed,
        robot_did,
        ODD_CONFORMANCE_TYPE,
        json!({
            "id": robot_did,
            "intervalIndex": interval_index,
            "observed": observed,
            "inDomain": result.ok,
            "reasons": result.reasons,
        }),
        valid_from,
        valid_until,
    )
}

/// Verify an `ODDConformanceAttestation`: the proof bound to the robot as
/// issuer (who must also be `credentialSubject.id`), validFrom present and the
/// window current, `inDomain` a boolean, and recomputing [`check_in_domain`]
/// over the attested observations against `domain` (required: the certified
/// domain) reproduces the attested verdict.
pub fn verify_odd_conformance(
    credential: &Value,
    robot_keys: Keys<'_>,
    domain: &Value,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    let v = match rv::verify_robotics_credential(
        credential,
        robot_keys,
        Some(ODD_CONFORMANCE_TYPE),
        now,
        VerifyOptions::window(Window::FromRequired),
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
        return Ok(None);
    }
    let claimed = match v.subject.get("inDomain") {
        Some(Value::Bool(b)) => *b,
        _ => return Ok(None),
    };
    let observed = match v.subject.get("observed") {
        Some(o @ Value::Object(_)) => o,
        _ => return Ok(None),
    };
    if !domain.is_object() || check_in_domain(domain, observed).ok != claimed {
        return Ok(None);
    }
    Ok(Some(v.subject))
}

/// True when a handover's force and speed fit the near-human envelope of
/// `scope`: the scope must be well-formed, force and speed finite and
/// non-negative, force within `maxForceN`, and speed within the lower of
/// `maxSpeedNearHumansMps` and `maxSpeedMps`.
pub fn handover_in_envelope(force_n: &Value, speed_mps: &Value, scope: &Value) -> bool {
    if !scope_problems(scope).is_empty() {
        return false;
    }
    let (f, s) = match (
        rv::finite_number(Some(force_n)),
        rv::finite_number(Some(speed_mps)),
    ) {
        (Some(f), Some(s)) if f >= 0.0 && s >= 0.0 => (f, s),
        _ => return false,
    };
    let cap = |k: &str| scope.get(k).and_then(|v| v.as_f64());
    if cap("maxForceN").is_some_and(|c| f > c) {
        return false;
    }
    let caps: Vec<f64> = ["maxSpeedNearHumansMps", "maxSpeedMps"]
        .iter()
        .filter_map(|k| cap(k))
        .collect();
    !caps.iter().any(|c| s > *c)
}

/// Parameters for [`build_human_handover`]. When `scope` is given the
/// near-human envelope verdict is computed and carried as `inEnvelope`.
#[derive(Debug, Clone)]
pub struct BuildHumanHandover {
    pub robot_did: String,
    pub recipient: String,
    pub object_id: String,
    pub force_n: f64,
    pub speed_mps: f64,
    pub scope: Option<Value>,
    pub valid_from: String,
    pub valid_until: Option<String>,
}

/// Build a signed `HumanHandoverCredential` (issued by the robot).
pub fn build_human_handover(robot_seed: &[u8], params: &BuildHumanHandover) -> Result<Value> {
    if params.robot_did.is_empty() || params.recipient.is_empty() || params.object_id.is_empty() {
        return Err(CoreError::Json(
            "robot_did, recipient, and object_id are required".into(),
        ));
    }
    let mut subject = json!({
        "id": params.robot_did,
        "recipient": params.recipient,
        "objectId": params.object_id,
        "envelope": {"forceN": params.force_n, "speedMps": params.speed_mps},
    });
    if let Some(scope) = &params.scope {
        subject["inEnvelope"] = json!(handover_in_envelope(
            &json!(params.force_n),
            &json!(params.speed_mps),
            scope
        ));
    }
    sign(
        robot_seed,
        &params.robot_did,
        HUMAN_HANDOVER_TYPE,
        subject,
        &params.valid_from,
        params.valid_until.as_deref(),
    )
}

/// Verify a `HumanHandoverCredential`: the proof bound to the robot as issuer
/// (who must also be `credentialSubject.id`), validFrom present and the window
/// current, finite envelope numbers, and, when `scope` is given, recomputing the
/// envelope check reproduces the attested `inEnvelope` (a credential that
/// states no verdict must be inside).
pub fn verify_human_handover(
    credential: &Value,
    robot_keys: Keys<'_>,
    scope: Option<&Value>,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    let v = match rv::verify_robotics_credential(
        credential,
        robot_keys,
        Some(HUMAN_HANDOVER_TYPE),
        now,
        VerifyOptions::window(Window::FromRequired),
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
        return Ok(None);
    }
    let env = match v.subject.get("envelope").and_then(|e| e.as_object()) {
        Some(e) => e,
        None => return Ok(None),
    };
    let (f, s) = match (env.get("forceN"), env.get("speedMps")) {
        (Some(f), Some(s))
            if rv::finite_number(Some(f)).is_some() && rv::finite_number(Some(s)).is_some() =>
        {
            (f, s)
        }
        _ => return Ok(None),
    };
    if let Some(scope) = scope {
        let claimed = match v.subject.get("inEnvelope") {
            None => true,
            Some(Value::Bool(b)) => *b,
            _ => return Ok(None),
        };
        if handover_in_envelope(f, s, scope) != claimed {
            return Ok(None);
        }
    }
    Ok(Some(v.subject))
}

/// Build a signed `HandoverAcknowledgement`: the recipient confirms receiving
/// the object of `handover`, bound to it by its proof value.
pub fn build_handover_ack(
    recipient_seed: &[u8],
    recipient_did: &str,
    handover: &Value,
    valid_from: &str,
) -> Result<Value> {
    let r = handover
        .get("proof")
        .and_then(|p| p.get("proofValue"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());
    let r = match r {
        Some(r) if !recipient_did.is_empty() => r,
        _ => {
            return Err(CoreError::Json(
                "recipient_did and a signed handover are required".into(),
            ))
        }
    };
    let object_id = handover
        .get("credentialSubject")
        .and_then(|s| s.get("objectId"))
        .cloned()
        .unwrap_or(Value::Null);
    sign(
        recipient_seed,
        recipient_did,
        HANDOVER_ACK_TYPE,
        json!({"id": recipient_did, "handoverRef": r, "objectId": object_id}),
        valid_from,
        None,
    )
}

/// Verify a `HandoverAcknowledgement`: the proof bound to the issuer, who must
/// be its subject and the recipient `handover` names, the window current, and
/// the acknowledgement bound to `handover` by its proof value.
pub fn verify_handover_ack(
    ack: &Value,
    recipient_keys: Keys<'_>,
    handover: &Value,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    let v = match rv::verify_robotics_credential(
        ack,
        recipient_keys,
        Some(HANDOVER_ACK_TYPE),
        now,
        VerifyOptions::window(Window::FromRequired),
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if v.subject.get("id").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
        return Ok(None);
    }
    let hs = match handover
        .get("credentialSubject")
        .and_then(|s| s.as_object())
    {
        Some(s) => s,
        None => return Ok(None),
    };
    if hs.get("recipient").and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
        return Ok(None);
    }
    let r = handover
        .get("proof")
        .and_then(|p| p.as_object())
        .and_then(|p| p.get("proofValue"))
        .and_then(|x| x.as_str())
        .filter(|s| !s.is_empty());
    match r {
        Some(r) if v.subject.get("handoverRef").and_then(|x| x.as_str()) == Some(r) => {
            Ok(Some(v.subject))
        }
        _ => Ok(None),
    }
}

// ---------------------------------------------------------------------------
// Swarm membership and collective action (port of `vouch/robotics/swarm.py`)
// ---------------------------------------------------------------------------

pub const SWARM_MEMBERSHIP_TYPE: &str = "SwarmMembershipCredential";
pub const COLLECTIVE_ACTION_TYPE: &str = "CollectiveActionAttestation";

/// Build a signed `SwarmMembershipCredential`: the coordinator admits
/// `robot_did` to `swarm_id`, optionally with a `role`.
pub fn build_swarm_membership(
    coordinator_seed: &[u8],
    coordinator_did: &str,
    swarm_id: &str,
    robot_did: &str,
    role: Option<&str>,
    valid_from: &str,
    valid_until: Option<&str>,
) -> Result<Value> {
    if swarm_id.is_empty() || robot_did.is_empty() {
        return Err(CoreError::Json(
            "swarm_id and robot_did are required".into(),
        ));
    }
    let mut subject = json!({"id": robot_did, "swarmId": swarm_id});
    if let Some(r) = role {
        subject["role"] = json!(r);
    }
    sign(
        coordinator_seed,
        coordinator_did,
        SWARM_MEMBERSHIP_TYPE,
        subject,
        valid_from,
        valid_until,
    )
}

/// Verify a `SwarmMembershipCredential` bound to the coordinator as issuer,
/// validFrom present and the window current, a non-empty `swarmId` and `id`,
/// and (when given) for `swarm_id` and issued by `coordinator_did`.
pub fn verify_swarm_membership(
    credential: &Value,
    coordinator_keys: Keys<'_>,
    swarm_id: Option<&str>,
    coordinator_did: Option<&str>,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    // A named coordinator is a trusted set of one: with no key, a did:key
    // coordinator verifies under its own key only when named here.
    let named: Option<std::collections::HashSet<String>> =
        coordinator_did.map(|c| [c.to_string()].into_iter().collect());
    let v = match rv::verify_robotics_credential(
        credential,
        coordinator_keys,
        Some(SWARM_MEMBERSHIP_TYPE),
        now,
        VerifyOptions {
            trusted_issuers: named.as_ref(),
            ..VerifyOptions::window(Window::FromRequired)
        },
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    let s = |k: &str| {
        v.subject
            .get(k)
            .and_then(|x| x.as_str())
            .filter(|x| !x.is_empty())
    };
    if s("swarmId").is_none() || s("id").is_none() {
        return Ok(None);
    }
    if swarm_id.is_some_and(|w| s("swarmId") != Some(w)) {
        return Ok(None);
    }
    if coordinator_did.is_some_and(|c| c != v.issuer) {
        return Ok(None);
    }
    Ok(Some(v.subject))
}

/// Build a signed `CollectiveActionAttestation`: the coordinator records that
/// `participants` took `action` together as `swarm_id`.
pub fn build_collective_action(
    coordinator_seed: &[u8],
    coordinator_did: &str,
    swarm_id: &str,
    action: &str,
    participants: &[String],
    valid_from: &str,
    valid_until: Option<&str>,
) -> Result<Value> {
    if swarm_id.is_empty() || action.is_empty() {
        return Err(CoreError::Json("swarm_id and action are required".into()));
    }
    if participants.is_empty() {
        return Err(CoreError::Json(
            "participants must be a non-empty list".into(),
        ));
    }
    sign(
        coordinator_seed,
        coordinator_did,
        COLLECTIVE_ACTION_TYPE,
        json!({"swarmId": swarm_id, "action": action, "participants": participants}),
        valid_from,
        valid_until,
    )
}

/// Verify a `CollectiveActionAttestation` bound to the coordinator, with a
/// swarm id and a non-empty list of participant DIDs. With `memberships`,
/// every participant must hold a membership in the same swarm from the same
/// coordinator that was valid at the action's validFrom. Returns
/// `(ok, unverified participants)`.
pub fn verify_collective_action(
    credential: &Value,
    coordinator_keys: Keys<'_>,
    memberships: Option<&[Value]>,
    now_iso: &str,
) -> Result<(bool, Vec<String>)> {
    let now = rv::require_now(now_iso)?;
    let v = match rv::verify_robotics_credential(
        credential,
        coordinator_keys,
        Some(COLLECTIVE_ACTION_TYPE),
        now,
        VerifyOptions::window(Window::FromRequired),
    ) {
        Ok(v) => v,
        Err(_) => return Ok((false, Vec::new())),
    };
    let swarm_id = match v.subject.get("swarmId").and_then(|x| x.as_str()) {
        Some(w) if !w.is_empty() => w.to_string(),
        _ => return Ok((false, Vec::new())),
    };
    let participants: Vec<String> = match v.subject.get("participants").and_then(|p| p.as_array()) {
        Some(a) if !a.is_empty() && a.iter().all(|x| x.as_str().is_some_and(|s| !s.is_empty())) => {
            a.iter().map(|x| x.as_str().unwrap().to_string()).collect()
        }
        _ => return Ok((false, Vec::new())),
    };
    let memberships = match memberships {
        None => return Ok((true, Vec::new())),
        Some(m) => m,
    };
    let action_at = match credential.get("validFrom").and_then(|x| x.as_str()) {
        Some(t) if rv::time_ns(credential.get("validFrom")).is_some() => t.to_string(),
        _ => return Ok((false, Vec::new())),
    };
    let mut covered = std::collections::HashSet::new();
    for m in memberships {
        if let Some(sub) = verify_swarm_membership(
            m,
            coordinator_keys,
            Some(&swarm_id),
            Some(&v.issuer),
            &action_at,
        )? {
            if let Some(id) = sub.get("id").and_then(|x| x.as_str()) {
                covered.insert(id.to_string());
            }
        }
    }
    let unverified: Vec<String> = participants
        .into_iter()
        .filter(|p| !covered.contains(p))
        .collect();
    Ok((unverified.is_empty(), unverified))
}

// ---------------------------------------------------------------------------
// Teleoperation control handoff (port of `vouch/robotics/teleop.py`)
// ---------------------------------------------------------------------------

pub const CONTROL_HANDOFF_TYPE: &str = "ControlHandoffCredential";
/// Control modes an interoperable verifier accepts.
pub const CONTROL_MODES: [&str; 3] = ["autonomous", "teleoperated", "shared"];

/// Parameters for [`build_control_handoff`]: the receiving controller
/// `to_controller` (the signer) takes control of `robot_did` under `mode`.
#[derive(Debug, Clone)]
pub struct BuildControlHandoff {
    pub robot_did: String,
    pub from_controller: String,
    pub to_controller: String,
    pub mode: String,
    pub valid_from: String,
    pub valid_until: Option<String>,
    pub prev_handoff_id: Option<String>,
    pub credential_id: String,
}

/// Build a signed `ControlHandoffCredential` (issued by the receiver).
pub fn build_control_handoff(receiver_seed: &[u8], p: &BuildControlHandoff) -> Result<Value> {
    if p.robot_did.is_empty() || p.from_controller.is_empty() || p.to_controller.is_empty() {
        return Err(CoreError::Json(
            "robot_did, from_controller, and to_controller are required".into(),
        ));
    }
    if !CONTROL_MODES.contains(&p.mode.as_str()) {
        return Err(CoreError::Json(format!(
            "mode must be one of {CONTROL_MODES:?}"
        )));
    }
    if p.credential_id.is_empty() {
        return Err(CoreError::Json("credential_id is required".into()));
    }
    let mut subject = json!({
        "id": p.robot_did, "fromController": p.from_controller,
        "toController": p.to_controller, "mode": p.mode,
    });
    if let Some(prev) = &p.prev_handoff_id {
        subject["prevHandoffId"] = json!(prev);
    }
    rv::require_now(&p.valid_from)?;
    let mut cred = Map::new();
    cred.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
    cred.insert("id".into(), json!(p.credential_id));
    cred.insert(
        "type".into(),
        json!(["VerifiableCredential", CONTROL_HANDOFF_TYPE]),
    );
    cred.insert("issuer".into(), json!(p.to_controller));
    cred.insert("validFrom".into(), json!(p.valid_from));
    if let Some(vu) = &p.valid_until {
        cred.insert("validUntil".into(), json!(vu));
    }
    cred.insert("credentialSubject".into(), subject);
    let opts = BuildProofOptions::new(format!("{}#key-1", p.to_controller), &p.valid_from);
    data_integrity::sign(&Value::Object(cred), receiver_seed, &opts)
}

/// Verify a control handoff: bound to the issuer, who must be `toController`,
/// non-empty `id` / `fromController` / `toController`, a known mode, the
/// window current, and (when given) for `robot_did`.
pub fn verify_control_handoff(
    credential: &Value,
    receiver_keys: Keys<'_>,
    robot_did: Option<&str>,
    now_iso: &str,
) -> Result<Option<Value>> {
    let now = rv::require_now(now_iso)?;
    let v = match rv::verify_robotics_credential(
        credential,
        receiver_keys,
        Some(CONTROL_HANDOFF_TYPE),
        now,
        VerifyOptions::window(Window::FromRequired),
    ) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    let s = |k: &str| {
        v.subject
            .get(k)
            .and_then(|x| x.as_str())
            .filter(|x| !x.is_empty())
    };
    if s("id").is_none()
        || s("fromController").is_none()
        || s("toController") != Some(v.issuer.as_str())
    {
        return Ok(None);
    }
    if !s("mode").is_some_and(|m| CONTROL_MODES.contains(&m)) {
        return Ok(None);
    }
    if robot_did.is_some_and(|r| s("id") != Some(r)) {
        return Ok(None);
    }
    Ok(Some(v.subject))
}

/// Verify an ordered list of control handoffs for `robot_did`: each verifies
/// under its receiver's key, toController matches the next fromController,
/// each later link names the previous `id` as `prevHandoffId`, links are in
/// time order, the first fromController is `origin_controller`, and each
/// earlier link was still valid when the next began (the last at `now_iso`).
/// Returns `(ok, current_controller)`. `origin_controller` is required: with no
/// known first controller, anyone could sign a first link taking control from
/// themselves.
pub fn verify_control_chain(
    handoffs: &[Value],
    keys: Keys<'_>,
    robot_did: &str,
    origin_controller: Option<&str>,
    now_iso: &str,
) -> Result<(bool, Option<String>)> {
    rv::require_now(now_iso)?;
    if robot_did.is_empty() || origin_controller.is_none_or(str::is_empty) {
        return Ok((false, None));
    }
    let mut expected: Option<String> = origin_controller.map(String::from);
    let mut current: Option<String> = origin_controller.map(String::from);
    let mut prev_id: Option<String> = None;
    let mut prev_time: Option<i128> = None;
    for (i, h) in handoffs.iter().enumerate() {
        let at = match handoffs.get(i + 1) {
            Some(n) => match n.get("validFrom").and_then(|x| x.as_str()) {
                Some(t) if rv::time_ns(n.get("validFrom")).is_some() => t.to_string(),
                _ => return Ok((false, None)),
            },
            None => now_iso.to_string(),
        };
        let sub = match verify_control_handoff(h, keys, Some(robot_did), &at)? {
            Some(s) => s,
            None => return Ok((false, None)),
        };
        if let Some(e) = &expected {
            if sub.get("fromController").and_then(|x| x.as_str()) != Some(e.as_str()) {
                return Ok((false, None));
            }
        }
        match rv::time_ns(h.get("validFrom")) {
            Some(t) if prev_time.is_none_or(|p| t >= p) => prev_time = Some(t),
            _ => return Ok((false, None)),
        }
        if i > 0 {
            match &prev_id {
                Some(p) if sub.get("prevHandoffId").and_then(|x| x.as_str()) == Some(p) => {}
                _ => return Ok((false, None)),
            }
        }
        prev_id = h
            .get("id")
            .and_then(|x| x.as_str())
            .filter(|x| !x.is_empty())
            .map(String::from);
        current = sub
            .get("toController")
            .and_then(|x| x.as_str())
            .map(String::from);
        expected = current.clone();
    }
    Ok((true, current))
}

/// The controller in charge at protocol time `at`: the toController of the
/// most recent handoff at or before `at` (handoffs in chain order).
pub fn controller_at(handoffs: &[Value], at: &str) -> Option<String> {
    let when = crate::time::parse_protocol_time_ns(at).ok()?;
    let mut holder = None;
    for h in handoffs {
        if rv::time_ns(h.get("validFrom")).is_some_and(|t| t <= when) {
            // A malformed link (no subject object, a non-string controller)
            // names nobody and leaves the holder as it was.
            if let Some(to) = h
                .get("credentialSubject")
                .and_then(|s| s.get("toController"))
                .and_then(|x| x.as_str())
            {
                holder = Some(to.to_string());
            }
        }
    }
    holder
}

/// Confirm the control timeline is continuous and single-held: each later
/// handoff's fromController is the previous toController. Returns `(ok,
/// seams)` where each seam is `{expected, found}`.
pub fn check_control_continuity(handoffs: &[Value]) -> (bool, Vec<Value>) {
    let mut seams = Vec::new();
    let mut prev_to: Option<String> = None;
    for h in handoffs {
        // A link with no subject object makes the timeline unaccountable.
        let sub = match h.get("credentialSubject").and_then(|s| s.as_object()) {
            Some(s) => s,
            None => return (false, seams),
        };
        let frm = sub.get("fromController").and_then(|x| x.as_str());
        if let Some(p) = &prev_to {
            if frm != Some(p.as_str()) {
                seams.push(json!({"expected": p, "found": frm.unwrap_or_default()}));
            }
        }
        prev_to = sub
            .get("toController")
            .and_then(|x| x.as_str())
            .map(String::from);
    }
    (seams.is_empty(), seams)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::Ed25519KeyPair;
    use crate::robotics_verify::test_keys::TNOW;
    use std::collections::BTreeMap;

    const T0: &str = "2026-01-01T00:00:00Z";

    fn party(b: u8, did: &str) -> (Vec<u8>, BTreeMap<String, Vec<u8>>) {
        let seed = vec![b; 32];
        let kp = Ed25519KeyPair::from_seed_slice(&seed).unwrap();
        (
            seed,
            BTreeMap::from([(did.to_string(), kp.public_key().to_vec())]),
        )
    }

    #[test]
    fn odd_round_trip_and_recomputed_verdict() {
        let (op, okeys) = party(1, "did:web:op.example.com");
        let (rb, rkeys) = party(2, "did:web:robot.example.com");
        let domain = json!({"maxSpeedMps": 1.0, "allowedZones": ["a"]});
        let cred = build_odd_credential(
            &op,
            "did:web:op.example.com",
            "did:web:robot.example.com",
            &domain,
            T0,
            None,
        )
        .unwrap();
        let got = verify_odd_credential(
            &cred,
            Keys::Map(&okeys),
            Some("did:web:robot.example.com"),
            None,
            TNOW,
        )
        .unwrap();
        assert_eq!(got, Some(domain.clone()));
        let observed = json!({"maxSpeedMps": 2.0, "zones": ["a"]});
        let att = build_odd_conformance(
            &rb,
            "did:web:robot.example.com",
            &domain,
            &observed,
            1,
            T0,
            None,
        )
        .unwrap();
        assert_eq!(att["credentialSubject"]["inDomain"], json!(false));
        assert!(
            verify_odd_conformance(&att, Keys::Map(&rkeys), &domain, TNOW)
                .unwrap()
                .is_some()
        );
        let looser = json!({"maxSpeedMps": 5.0, "allowedZones": ["a"]});
        assert!(
            verify_odd_conformance(&att, Keys::Map(&rkeys), &looser, TNOW)
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn handover_round_trip_and_ack_binding() {
        let (rb, rkeys) = party(3, "did:web:robot.example.com");
        let (pp, pkeys) = party(4, "did:web:person.example.com");
        let scope = json!({"maxForceN": 20.0, "maxSpeedNearHumansMps": 0.25});
        let p = BuildHumanHandover {
            robot_did: "did:web:robot.example.com".into(),
            recipient: "did:web:person.example.com".into(),
            object_id: "cup".into(),
            force_n: 5.0,
            speed_mps: 0.2,
            scope: Some(scope.clone()),
            valid_from: T0.into(),
            valid_until: None,
        };
        let ho = build_human_handover(&rb, &p).unwrap();
        assert_eq!(ho["credentialSubject"]["inEnvelope"], json!(true));
        assert!(
            verify_human_handover(&ho, Keys::Map(&rkeys), Some(&scope), TNOW)
                .unwrap()
                .is_some()
        );
        let fast = build_human_handover(
            &rb,
            &BuildHumanHandover {
                speed_mps: 0.5,
                ..p.clone()
            },
        )
        .unwrap();
        assert_eq!(fast["credentialSubject"]["inEnvelope"], json!(false));
        let ack = build_handover_ack(&pp, "did:web:person.example.com", &ho, T0).unwrap();
        assert!(verify_handover_ack(&ack, Keys::Map(&pkeys), &ho, TNOW)
            .unwrap()
            .is_some());
        assert!(verify_handover_ack(&ack, Keys::Map(&pkeys), &fast, TNOW)
            .unwrap()
            .is_none());
        assert!(!handover_in_envelope(&json!(f64::NAN), &json!(0.1), &scope));
    }
}