1#![forbid(unsafe_code)]
8
9use alloc::collections::BTreeMap;
10use alloc::collections::BTreeSet;
11use alloc::string::String;
12use alloc::vec::Vec;
13use core::fmt;
14
15use crate::causal_kernel::{self as kernel, Decision, FanIn, Lookup};
16use crate::message::CausedBy;
17use crate::store::{ContentHash, MessageStore, ThreadId};
18
19pub const BEGIN_KEYWORD: &str = "begin";
28
29pub const REPEAT_SEPARATOR: char = '#';
40
41pub fn repeat_base_name(name: &str) -> &str {
55 match name.find(REPEAT_SEPARATOR) {
56 Some(idx) => &name[..idx],
57 None => name,
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub enum NodeRef {
73 Single(String),
74 Any(BTreeSet<String>),
75 All(BTreeSet<String>),
76}
77
78impl NodeRef {
79 pub fn performatives(&self) -> impl Iterator<Item = &str> {
81 match self {
82 NodeRef::Single(s) => {
83 let v: Vec<&str> = alloc::vec![s.as_str()];
84 v.into_iter()
85 }
86 NodeRef::Any(set) | NodeRef::All(set) => {
87 let v: Vec<&str> = set.iter().map(|s| s.as_str()).collect();
88 v.into_iter()
89 }
90 }
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
99#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
100pub struct StepDecl {
101 pub performative: String,
102 pub predecessors: Vec<NodeRef>,
103 pub successors: Vec<NodeRef>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub struct CausalProtocol {
113 pub steps: BTreeMap<String, StepDecl>,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
119pub enum ProtocolViolation {
120 Cycle { participants: Vec<String> },
122 Unreachable { step: String },
124 UndefinedPerformative { name: String },
126 DuplicateStep { name: String },
128}
129
130impl fmt::Display for ProtocolViolation {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 match self {
133 Self::Cycle { participants } => {
134 write!(f, "cycle detected: {}", participants.join(" → "))
135 }
136 Self::Unreachable { step } => {
137 write!(f, "step '{}' is unreachable from begin", step)
138 }
139 Self::UndefinedPerformative { name } => {
140 write!(f, "performative '{}' is not defined", name)
141 }
142 Self::DuplicateStep { name } => {
143 write!(f, "duplicate step declaration for '{}'", name)
144 }
145 }
146 }
147}
148
149fn has_duplicate(refs: &[NodeRef]) -> bool {
150 for i in 0..refs.len() {
151 for j in (i + 1)..refs.len() {
152 if refs[i] == refs[j] {
153 return true;
154 }
155 }
156 }
157 false
158}
159
160impl CausalProtocol {
161 fn all_referenced_performatives(&self) -> BTreeSet<String> {
164 let mut names = BTreeSet::new();
165 for (name, step) in &self.steps {
166 if name != BEGIN_KEYWORD {
167 names.insert(name.clone());
168 }
169 for nr in step.predecessors.iter().chain(step.successors.iter()) {
170 for p in nr.performatives() {
171 if p != BEGIN_KEYWORD {
172 names.insert(p.into());
173 }
174 }
175 }
176 }
177 names
178 }
179
180 fn successor_graph(&self) -> BTreeMap<&str, BTreeSet<&str>> {
182 let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
183 for (name, step) in &self.steps {
184 graph.entry(name.as_str()).or_default();
185 for nr in &step.successors {
186 for s in nr.performatives() {
187 graph.entry(name.as_str()).or_default().insert(s);
188 graph.entry(s).or_default();
189 }
190 }
191 }
192 graph
193 }
194
195 pub fn check_acyclicity(&self) -> Vec<ProtocolViolation> {
200 let graph = self.successor_graph();
201
202 let mut color: BTreeMap<&str, u8> = BTreeMap::new();
204 let mut path: Vec<&str> = Vec::new();
205 let mut violations = Vec::new();
206
207 for &node in graph.keys() {
208 if *color.get(node).unwrap_or(&0) == 0 {
209 Self::dfs_cycle(node, &graph, &mut color, &mut path, &mut violations);
210 }
211 }
212 violations
213 }
214
215 fn dfs_cycle<'a>(
216 node: &'a str,
217 graph: &BTreeMap<&'a str, BTreeSet<&'a str>>,
218 color: &mut BTreeMap<&'a str, u8>,
219 path: &mut Vec<&'a str>,
220 violations: &mut Vec<ProtocolViolation>,
221 ) {
222 color.insert(node, 1); path.push(node);
224
225 if let Some(neighbors) = graph.get(node) {
226 for &next in neighbors {
227 match color.get(next).unwrap_or(&0) {
228 0 => Self::dfs_cycle(next, graph, color, path, violations),
229 1 => {
230 if let Some(pos) = path.iter().position(|&n| n == next) {
232 let cycle: Vec<String> =
233 path[pos..].iter().map(|s| String::from(*s)).collect();
234 violations.push(ProtocolViolation::Cycle {
235 participants: cycle,
236 });
237 }
238 }
239 _ => {} }
241 }
242 }
243
244 path.pop();
245 color.insert(node, 2); }
247
248 pub fn check_reachability(&self) -> Vec<ProtocolViolation> {
252 let graph = self.successor_graph();
253 let mut visited: BTreeSet<&str> = BTreeSet::new();
254 let mut queue: Vec<&str> = Vec::new();
255
256 if graph.contains_key(BEGIN_KEYWORD) {
257 queue.push(BEGIN_KEYWORD);
258 visited.insert(BEGIN_KEYWORD);
259 }
260
261 while let Some(current) = queue.pop() {
262 if let Some(neighbors) = graph.get(current) {
263 for &next in neighbors {
264 if visited.insert(next) {
265 queue.push(next);
266 }
267 }
268 }
269 }
270
271 let mut violations = Vec::new();
272 for name in self.steps.keys() {
273 if name != BEGIN_KEYWORD && !visited.contains(name.as_str()) {
274 violations.push(ProtocolViolation::Unreachable { step: name.clone() });
275 }
276 }
277 violations
278 }
279
280 pub fn check_performative_definedness(
285 &self,
286 defined_performatives: &[&str],
287 ) -> Vec<ProtocolViolation> {
288 let defined: BTreeSet<&str> = defined_performatives.iter().copied().collect();
289 let referenced = self.all_referenced_performatives();
290
291 let mut flagged: BTreeSet<&str> = BTreeSet::new();
295 let mut violations = Vec::new();
296 for name in &referenced {
297 let base = repeat_base_name(name);
298 if !defined.contains(base) && flagged.insert(base) {
299 violations.push(ProtocolViolation::UndefinedPerformative {
300 name: String::from(base),
301 });
302 }
303 }
304 violations
305 }
306
307 pub fn expansion_size(&self) -> u32 {
314 let n = self
315 .steps
316 .keys()
317 .filter(|name| name.as_str() != BEGIN_KEYWORD)
318 .count();
319 u32::try_from(n).unwrap_or(u32::MAX)
320 }
321
322 pub fn check_step_uniqueness(&self) -> Vec<ProtocolViolation> {
342 let mut violations = Vec::new();
343 for (name, step) in &self.steps {
344 if has_duplicate(&step.predecessors) || has_duplicate(&step.successors) {
345 violations.push(ProtocolViolation::DuplicateStep { name: name.clone() });
346 }
347 }
348 violations
349 }
350
351 pub fn verify_r5_protocol(&self, defined_performatives: &[&str]) -> Vec<ProtocolViolation> {
356 let mut violations = Vec::new();
357 violations.extend(self.check_step_uniqueness());
358 violations.extend(self.check_acyclicity());
359 violations.extend(self.check_reachability());
360 violations.extend(self.check_performative_definedness(defined_performatives));
361 violations
362 }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq)]
367#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
368pub enum CausalViolation {
369 UnknownPredecessor { caused_by: String },
371 InvalidPredecessor {
373 caused_by: String,
374 expected: Vec<String>,
375 found: String,
376 },
377 MissingCausedBy,
379 IncompleteFanIn { missing_types: Vec<String> },
381 ExtraneousPredecessor { caused_by: String, found: String },
383 FanInWithoutAllDecl { performative: String },
385 RoleConformance { reason: String },
387}
388
389impl fmt::Display for CausalViolation {
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 match self {
392 Self::UnknownPredecessor { caused_by } => {
393 write!(f, "unknown predecessor: {caused_by}")
394 }
395 Self::InvalidPredecessor {
396 caused_by,
397 expected,
398 found,
399 } => {
400 write!(
401 f,
402 "invalid predecessor {caused_by}: expected one of [{}], found {found}",
403 expected.join(", ")
404 )
405 }
406 Self::MissingCausedBy => write!(f, "missing :caused-by"),
407 Self::IncompleteFanIn { missing_types } => {
408 write!(
409 f,
410 "incomplete fan-in: missing types [{}]",
411 missing_types.join(", ")
412 )
413 }
414 Self::ExtraneousPredecessor { caused_by, found } => {
415 write!(f, "extraneous predecessor {caused_by}: found {found}")
416 }
417 Self::FanInWithoutAllDecl { performative } => {
418 write!(f, "fan-in without (all ...) declaration for {performative}")
419 }
420 Self::RoleConformance { reason } => {
421 write!(f, "role conformance: {reason}")
422 }
423 }
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq)]
438#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
439pub enum VerificationResult {
440 Unknown,
442 Valid,
444 Violation(CausalViolation),
446}
447
448impl VerificationResult {
449 pub fn meet(self, other: VerificationResult) -> VerificationResult {
459 match (&self, &other) {
460 (VerificationResult::Violation(_), _) => self,
461 (_, VerificationResult::Violation(_)) => other,
462 (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
463 VerificationResult::Unknown
464 }
465 (VerificationResult::Valid, VerificationResult::Valid) => VerificationResult::Valid,
466 }
467 }
468
469 pub fn join(self, other: VerificationResult) -> VerificationResult {
480 match (&self, &other) {
481 (VerificationResult::Valid, _) | (_, VerificationResult::Valid) => {
482 VerificationResult::Valid
483 }
484 (VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
485 VerificationResult::Unknown
486 }
487 (VerificationResult::Violation(_), VerificationResult::Violation(_)) => self,
488 }
489 }
490
491 pub fn is_resolved(&self) -> bool {
493 !matches!(self, VerificationResult::Unknown)
494 }
495
496 pub fn is_stable(&self) -> bool {
500 self.is_resolved()
501 }
502}
503
504impl PartialOrd for VerificationResult {
505 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
508 use core::cmp::Ordering;
509 match (self, other) {
510 (VerificationResult::Unknown, VerificationResult::Unknown) => Some(Ordering::Equal),
512 (VerificationResult::Valid, VerificationResult::Valid) => Some(Ordering::Equal),
513 (VerificationResult::Violation(_), VerificationResult::Violation(_)) => {
514 Some(Ordering::Equal)
515 }
516 (VerificationResult::Unknown, _) => Some(Ordering::Less),
518 (_, VerificationResult::Unknown) => Some(Ordering::Greater),
519 (VerificationResult::Valid, VerificationResult::Violation(_))
521 | (VerificationResult::Violation(_), VerificationResult::Valid) => None,
522 }
523 }
524}
525
526pub(crate) fn predecessor_type<'a, S: MessageStore>(
552 store: &'a S,
553 hash: &ContentHash,
554 thread: &ThreadId,
555) -> Option<&'a str> {
556 if let Some(predecessor_msg) = store.lookup_in_thread(hash, thread) {
557 return Some(
561 predecessor_msg
562 .innermost_simple()
563 .and_then(|m| m.performative())
564 .map(|p| p.name())
565 .unwrap_or(""),
566 );
567 }
568 if let Some(e) = store.envelope_in_thread(hash, thread) {
569 return Some(e.performative());
570 }
571 store
572 .opened_in_thread(hash, thread)
573 .and_then(|e| e.performative())
574}
575
576pub(crate) fn allowed_single_predecessors(step: &StepDecl) -> Vec<String> {
580 let mut types = Vec::new();
581 for nr in &step.predecessors {
582 match nr {
583 NodeRef::Single(s) => types.push(s.clone()),
584 NodeRef::Any(set) => types.extend(set.iter().cloned()),
585 NodeRef::All(_) => {} }
587 }
588 types
589}
590
591pub fn verify_causal<S: MessageStore>(
603 msg_performative: &str,
604 caused_by: Option<&CausedBy>,
605 store: &S,
606 protocol: &CausalProtocol,
607 thread: &ThreadId,
608) -> VerificationResult {
609 if crate::repeat::has_repeat(protocol) {
610 return crate::repeat::verify(msg_performative, caused_by, store, protocol, thread, None);
611 }
612 let step = match protocol.steps.get(msg_performative) {
613 Some(s) => s,
614 None => return VerificationResult::Valid,
616 };
617 let has_predecessors = !step.predecessors.is_empty();
618
619 match caused_by {
620 None => match kernel::absent(has_predecessors) {
621 Decision::Valid => VerificationResult::Valid,
622 Decision::MissingCausedBy => {
623 VerificationResult::Violation(CausalViolation::MissingCausedBy)
624 }
625 _ => unreachable!("absent decision"),
626 },
627 Some(CausedBy::Begin) => {
628 let begin_allowed = step.predecessors.iter().any(|nr| match nr {
629 NodeRef::Single(s) => s == BEGIN_KEYWORD,
630 NodeRef::Any(set) => set.contains(BEGIN_KEYWORD),
631 NodeRef::All(_) => false,
632 });
633 match kernel::literal_begin(begin_allowed) {
634 Decision::Valid => VerificationResult::Valid,
635 Decision::InvalidPredecessor => {
636 VerificationResult::Violation(CausalViolation::InvalidPredecessor {
637 caused_by: BEGIN_KEYWORD.into(),
638 expected: allowed_single_predecessors(step),
639 found: BEGIN_KEYWORD.into(),
640 })
641 }
642 _ => unreachable!("literal-begin decision"),
643 }
644 }
645 Some(CausedBy::Single(hash_str)) => {
646 let content_hash = ContentHash(hash_str.clone());
647 let pred_perf = predecessor_type(store, &content_hash, thread);
648 let allowed = if pred_perf.is_some() {
650 allowed_single_predecessors(step)
651 } else {
652 Vec::new()
653 };
654 let lookup = match pred_perf {
655 None => Lookup::Missing,
656 Some(p) if allowed.iter().any(|a| a == p) => Lookup::Allowed,
657 Some(_) => Lookup::Wrong,
658 };
659 match kernel::single(has_predecessors, lookup) {
660 Decision::Valid => VerificationResult::Valid,
661 Decision::Unknown => VerificationResult::Unknown,
662 Decision::ExtraneousPredecessor => {
663 VerificationResult::Violation(CausalViolation::ExtraneousPredecessor {
664 caused_by: hash_str.clone(),
665 found: pred_perf.expect("wrong lookup has a type").into(),
666 })
667 }
668 Decision::InvalidPredecessor => {
669 VerificationResult::Violation(CausalViolation::InvalidPredecessor {
670 caused_by: hash_str.clone(),
671 expected: allowed,
672 found: pred_perf.expect("wrong lookup has a type").into(),
673 })
674 }
675 _ => unreachable!("single decision"),
676 }
677 }
678 Some(CausedBy::Multiple(hashes)) => {
679 let all_decl = step.predecessors.iter().find_map(|nr| match nr {
681 NodeRef::All(set) => Some(set),
682 _ => None,
683 });
684 let mut state = FanIn::Clear;
685 let mut found_types = BTreeSet::new();
686 let mut first_error = None;
687 let mut missing = Vec::new();
688 if let Some(all_set) = all_decl {
689 for hash_str in hashes {
690 let content_hash = ContentHash(hash_str.clone());
691 let lookup = match predecessor_type(store, &content_hash, thread) {
692 None => Lookup::Missing,
693 Some(pred_perf) if all_set.contains(pred_perf) => {
694 found_types.insert(String::from(pred_perf));
695 Lookup::Allowed
696 }
697 Some(pred_perf) => {
698 if first_error.is_none() {
699 first_error = Some(CausalViolation::InvalidPredecessor {
700 caused_by: hash_str.clone(),
701 expected: all_set.iter().cloned().collect(),
702 found: pred_perf.into(),
703 });
704 }
705 Lookup::Wrong
706 }
707 };
708 state = kernel::observe(state, lookup);
709 }
710 if matches!(state, FanIn::Clear) {
711 missing = all_set
712 .iter()
713 .filter(|t| !found_types.contains(*t))
714 .cloned()
715 .collect();
716 }
717 }
718 match kernel::finish(all_decl.is_some(), state, missing.is_empty()) {
719 Decision::Valid => VerificationResult::Valid,
720 Decision::Unknown => VerificationResult::Unknown,
721 Decision::InvalidPredecessor => VerificationResult::Violation(
722 first_error.expect("wrong fan-in has a diagnostic"),
723 ),
724 Decision::IncompleteFanIn => {
725 VerificationResult::Violation(CausalViolation::IncompleteFanIn {
726 missing_types: missing,
727 })
728 }
729 Decision::FanInWithoutAllDecl => {
730 VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl {
731 performative: msg_performative.into(),
732 })
733 }
734 _ => unreachable!("fan-in decision"),
735 }
736 }
737 }
738}
739
740#[cfg(test)]
741mod tests {
742 use super::*;
743
744 #[test]
756 fn test_reserved_keyword_vocabulary_is_singleton() {
757 assert_eq!(BEGIN_KEYWORD, "begin");
758 }
759
760 fn violation() -> VerificationResult {
761 VerificationResult::Violation(CausalViolation::MissingCausedBy)
762 }
763
764 fn violation2() -> VerificationResult {
765 VerificationResult::Violation(CausalViolation::UnknownPredecessor {
766 caused_by: "f1220test".into(),
767 })
768 }
769
770 #[test]
775 fn test_construction_unknown() {
776 let r = VerificationResult::Unknown;
777 assert!(!r.is_resolved());
778 assert!(!r.is_stable());
779 }
780
781 #[test]
782 fn test_construction_valid() {
783 let r = VerificationResult::Valid;
784 assert!(r.is_resolved());
785 assert!(r.is_stable());
786 }
787
788 #[test]
789 fn test_construction_violation() {
790 let r = violation();
791 assert!(r.is_resolved());
792 assert!(r.is_stable());
793 }
794
795 #[test]
796 fn test_partial_ord_unknown_lt_valid() {
797 assert!(VerificationResult::Unknown < VerificationResult::Valid);
798 }
799
800 #[test]
801 fn test_partial_ord_unknown_lt_violation() {
802 assert!(VerificationResult::Unknown < violation());
803 }
804
805 #[test]
806 fn test_partial_ord_valid_violation_incomparable() {
807 let v = VerificationResult::Valid;
808 let viol = violation();
809 assert!(v.partial_cmp(&viol).is_none());
810 assert!(viol.partial_cmp(&v).is_none());
811 }
812
813 #[test]
814 fn test_partial_ord_reflexive() {
815 assert_eq!(
816 VerificationResult::Unknown.partial_cmp(&VerificationResult::Unknown),
817 Some(core::cmp::Ordering::Equal)
818 );
819 assert_eq!(
820 VerificationResult::Valid.partial_cmp(&VerificationResult::Valid),
821 Some(core::cmp::Ordering::Equal)
822 );
823 assert_eq!(
824 violation().partial_cmp(&violation()),
825 Some(core::cmp::Ordering::Equal)
826 );
827 }
828
829 #[test]
834 fn test_meet_unknown_unknown() {
835 assert_eq!(
836 VerificationResult::Unknown.meet(VerificationResult::Unknown),
837 VerificationResult::Unknown
838 );
839 }
840
841 #[test]
842 fn test_meet_unknown_valid() {
843 assert_eq!(
844 VerificationResult::Unknown.meet(VerificationResult::Valid),
845 VerificationResult::Unknown
846 );
847 }
848
849 #[test]
850 fn test_meet_unknown_violation() {
851 let result = VerificationResult::Unknown.meet(violation());
852 assert!(matches!(result, VerificationResult::Violation(_)));
853 }
854
855 #[test]
856 fn test_meet_valid_unknown() {
857 assert_eq!(
858 VerificationResult::Valid.meet(VerificationResult::Unknown),
859 VerificationResult::Unknown
860 );
861 }
862
863 #[test]
864 fn test_meet_valid_valid() {
865 assert_eq!(
866 VerificationResult::Valid.meet(VerificationResult::Valid),
867 VerificationResult::Valid
868 );
869 }
870
871 #[test]
872 fn test_meet_valid_violation() {
873 let result = VerificationResult::Valid.meet(violation());
874 assert!(matches!(result, VerificationResult::Violation(_)));
875 }
876
877 #[test]
878 fn test_meet_violation_unknown() {
879 let result = violation().meet(VerificationResult::Unknown);
880 assert!(matches!(result, VerificationResult::Violation(_)));
881 }
882
883 #[test]
884 fn test_meet_violation_valid() {
885 let result = violation().meet(VerificationResult::Valid);
886 assert!(matches!(result, VerificationResult::Violation(_)));
887 }
888
889 #[test]
890 fn test_meet_violation_violation() {
891 let result = violation().meet(violation2());
892 assert!(matches!(result, VerificationResult::Violation(_)));
893 }
894
895 #[test]
900 fn test_join_unknown_unknown() {
901 assert_eq!(
902 VerificationResult::Unknown.join(VerificationResult::Unknown),
903 VerificationResult::Unknown
904 );
905 }
906
907 #[test]
908 fn test_join_unknown_valid() {
909 assert_eq!(
910 VerificationResult::Unknown.join(VerificationResult::Valid),
911 VerificationResult::Valid
912 );
913 }
914
915 #[test]
916 fn test_join_unknown_violation() {
917 let result = VerificationResult::Unknown.join(violation());
918 assert_eq!(result, VerificationResult::Unknown);
919 }
920
921 #[test]
922 fn test_join_valid_unknown() {
923 assert_eq!(
924 VerificationResult::Valid.join(VerificationResult::Unknown),
925 VerificationResult::Valid
926 );
927 }
928
929 #[test]
930 fn test_join_valid_valid() {
931 assert_eq!(
932 VerificationResult::Valid.join(VerificationResult::Valid),
933 VerificationResult::Valid
934 );
935 }
936
937 #[test]
938 fn test_join_valid_violation() {
939 assert_eq!(
940 VerificationResult::Valid.join(violation()),
941 VerificationResult::Valid
942 );
943 }
944
945 #[test]
946 fn test_join_violation_unknown() {
947 let result = violation().join(VerificationResult::Unknown);
948 assert_eq!(result, VerificationResult::Unknown);
949 }
950
951 #[test]
952 fn test_join_violation_valid() {
953 assert_eq!(
954 violation().join(VerificationResult::Valid),
955 VerificationResult::Valid
956 );
957 }
958
959 #[test]
960 fn test_join_violation_violation() {
961 let result = violation().join(violation2());
962 assert!(matches!(result, VerificationResult::Violation(_)));
963 }
964
965 #[test]
970 fn test_causal_violation_display() {
971 let v = CausalViolation::MissingCausedBy;
972 assert_eq!(v.to_string(), "missing :caused-by");
973
974 let v = CausalViolation::UnknownPredecessor {
975 caused_by: "f1220abc".into(),
976 };
977 assert_eq!(v.to_string(), "unknown predecessor: f1220abc");
978 }
979
980 #[test]
981 fn test_causal_violation_variants_exist() {
982 let _ = CausalViolation::UnknownPredecessor {
983 caused_by: "h".into(),
984 };
985 let _ = CausalViolation::InvalidPredecessor {
986 caused_by: "h".into(),
987 expected: vec!["a".into()],
988 found: "b".into(),
989 };
990 let _ = CausalViolation::MissingCausedBy;
991 let _ = CausalViolation::IncompleteFanIn {
992 missing_types: vec!["a".into()],
993 };
994 let _ = CausalViolation::ExtraneousPredecessor {
995 caused_by: "h".into(),
996 found: "x".into(),
997 };
998 let _ = CausalViolation::FanInWithoutAllDecl {
999 performative: "p".into(),
1000 };
1001 }
1002
1003 #[test]
1008 fn test_meet_preserves_first_violation() {
1009 let v1 = violation();
1010 let v2 = violation2();
1011 let result = v1.meet(v2);
1013 assert_eq!(
1014 result,
1015 VerificationResult::Violation(CausalViolation::MissingCausedBy)
1016 );
1017 }
1018
1019 #[test]
1024 fn test_join_preserves_first_violation() {
1025 let v1 = violation();
1026 let result = v1.join(violation2());
1027 assert_eq!(
1028 result,
1029 VerificationResult::Violation(CausalViolation::MissingCausedBy)
1030 );
1031 }
1032
1033 fn linear_protocol() -> CausalProtocol {
1039 let mut steps = BTreeMap::new();
1040 steps.insert(
1041 "begin".into(),
1042 StepDecl {
1043 performative: "begin".into(),
1044 predecessors: vec![],
1045 successors: vec![NodeRef::Single("a".into())],
1046 },
1047 );
1048 steps.insert(
1049 "a".into(),
1050 StepDecl {
1051 performative: "a".into(),
1052 predecessors: vec![NodeRef::Single("begin".into())],
1053 successors: vec![NodeRef::Single("b".into())],
1054 },
1055 );
1056 steps.insert(
1057 "b".into(),
1058 StepDecl {
1059 performative: "b".into(),
1060 predecessors: vec![NodeRef::Single("a".into())],
1061 successors: vec![NodeRef::Single("c".into())],
1062 },
1063 );
1064 steps.insert(
1065 "c".into(),
1066 StepDecl {
1067 performative: "c".into(),
1068 predecessors: vec![NodeRef::Single("b".into())],
1069 successors: vec![],
1070 },
1071 );
1072 CausalProtocol { steps }
1073 }
1074
1075 #[test]
1078 fn test_acyclicity_linear_chain_passes() {
1079 let proto = linear_protocol();
1081 assert!(proto.check_acyclicity().is_empty());
1082 }
1083
1084 #[test]
1085 fn test_acyclicity_direct_cycle_rejected() {
1086 let mut steps = BTreeMap::new();
1088 steps.insert(
1089 "a".into(),
1090 StepDecl {
1091 performative: "a".into(),
1092 predecessors: vec![NodeRef::Single("b".into())],
1093 successors: vec![NodeRef::Single("b".into())],
1094 },
1095 );
1096 steps.insert(
1097 "b".into(),
1098 StepDecl {
1099 performative: "b".into(),
1100 predecessors: vec![NodeRef::Single("a".into())],
1101 successors: vec![NodeRef::Single("a".into())],
1102 },
1103 );
1104 let proto = CausalProtocol { steps };
1105 let violations = proto.check_acyclicity();
1106 assert!(!violations.is_empty());
1107 assert!(violations
1108 .iter()
1109 .any(|v| matches!(v, ProtocolViolation::Cycle { .. })));
1110 }
1111
1112 #[test]
1113 fn test_acyclicity_transitive_cycle_rejected() {
1114 let mut steps = BTreeMap::new();
1116 steps.insert(
1117 "a".into(),
1118 StepDecl {
1119 performative: "a".into(),
1120 predecessors: vec![NodeRef::Single("c".into())],
1121 successors: vec![NodeRef::Single("b".into())],
1122 },
1123 );
1124 steps.insert(
1125 "b".into(),
1126 StepDecl {
1127 performative: "b".into(),
1128 predecessors: vec![NodeRef::Single("a".into())],
1129 successors: vec![NodeRef::Single("c".into())],
1130 },
1131 );
1132 steps.insert(
1133 "c".into(),
1134 StepDecl {
1135 performative: "c".into(),
1136 predecessors: vec![NodeRef::Single("b".into())],
1137 successors: vec![NodeRef::Single("a".into())],
1138 },
1139 );
1140 let proto = CausalProtocol { steps };
1141 let violations = proto.check_acyclicity();
1142 assert!(!violations.is_empty());
1143 }
1144
1145 #[test]
1148 fn test_reachability_linear_chain_passes() {
1149 let proto = linear_protocol();
1150 assert!(proto.check_reachability().is_empty());
1151 }
1152
1153 #[test]
1154 fn test_reachability_both_from_begin_passes() {
1155 let mut steps = BTreeMap::new();
1157 steps.insert(
1158 "begin".into(),
1159 StepDecl {
1160 performative: "begin".into(),
1161 predecessors: vec![],
1162 successors: vec![NodeRef::Single("a".into()), NodeRef::Single("b".into())],
1163 },
1164 );
1165 steps.insert(
1166 "a".into(),
1167 StepDecl {
1168 performative: "a".into(),
1169 predecessors: vec![NodeRef::Single("begin".into())],
1170 successors: vec![],
1171 },
1172 );
1173 steps.insert(
1174 "b".into(),
1175 StepDecl {
1176 performative: "b".into(),
1177 predecessors: vec![NodeRef::Single("begin".into())],
1178 successors: vec![],
1179 },
1180 );
1181 let proto = CausalProtocol { steps };
1182 assert!(proto.check_reachability().is_empty());
1183 }
1184
1185 #[test]
1186 fn test_reachability_unreachable_step_rejected() {
1187 let mut steps = BTreeMap::new();
1189 steps.insert(
1190 "begin".into(),
1191 StepDecl {
1192 performative: "begin".into(),
1193 predecessors: vec![],
1194 successors: vec![NodeRef::Single("a".into())],
1195 },
1196 );
1197 steps.insert(
1198 "a".into(),
1199 StepDecl {
1200 performative: "a".into(),
1201 predecessors: vec![NodeRef::Single("begin".into())],
1202 successors: vec![],
1203 },
1204 );
1205 steps.insert(
1206 "c".into(),
1207 StepDecl {
1208 performative: "c".into(),
1209 predecessors: vec![NodeRef::Single("x".into())],
1210 successors: vec![],
1211 },
1212 );
1213 let proto = CausalProtocol { steps };
1214 let violations = proto.check_reachability();
1215 assert_eq!(violations.len(), 1);
1216 assert!(matches!(
1217 &violations[0],
1218 ProtocolViolation::Unreachable { step } if step == "c"
1219 ));
1220 }
1221
1222 #[test]
1225 fn test_definedness_all_defined_passes() {
1226 let proto = linear_protocol();
1227 let violations = proto.check_performative_definedness(&["a", "b", "c"]);
1228 assert!(violations.is_empty());
1229 }
1230
1231 #[test]
1232 fn test_definedness_undefined_rejected() {
1233 let proto = linear_protocol();
1234 let violations = proto.check_performative_definedness(&["a"]);
1236 assert_eq!(violations.len(), 2);
1237 let names: Vec<&str> = violations
1238 .iter()
1239 .filter_map(|v| match v {
1240 ProtocolViolation::UndefinedPerformative { name } => Some(name.as_str()),
1241 _ => None,
1242 })
1243 .collect();
1244 assert!(names.contains(&"b"));
1245 assert!(names.contains(&"c"));
1246 }
1247
1248 #[test]
1251 fn test_step_uniqueness_clean_protocol_passes() {
1252 let proto = linear_protocol();
1253 assert!(proto.check_step_uniqueness().is_empty());
1254 }
1255
1256 #[test]
1257 fn test_step_uniqueness_detects_duplicate_successor() {
1258 let mut steps = BTreeMap::new();
1260 steps.insert(
1261 "begin".into(),
1262 StepDecl {
1263 performative: "begin".into(),
1264 predecessors: vec![],
1265 successors: vec![NodeRef::Single("a".into()), NodeRef::Single("a".into())],
1266 },
1267 );
1268 steps.insert(
1269 "a".into(),
1270 StepDecl {
1271 performative: "a".into(),
1272 predecessors: vec![
1273 NodeRef::Single("begin".into()),
1274 NodeRef::Single("begin".into()),
1275 ],
1276 successors: vec![],
1277 },
1278 );
1279 let proto = CausalProtocol { steps };
1280 let violations = proto.check_step_uniqueness();
1281 let names: BTreeSet<&str> = violations
1282 .iter()
1283 .filter_map(|v| match v {
1284 ProtocolViolation::DuplicateStep { name } => Some(name.as_str()),
1285 _ => None,
1286 })
1287 .collect();
1288 assert!(names.contains("begin"));
1289 assert!(names.contains("a"));
1290 }
1291
1292 #[test]
1293 fn test_step_uniqueness_accepts_distinct_alternatives() {
1294 let mut steps = BTreeMap::new();
1301 steps.insert(
1302 "a".into(),
1303 StepDecl {
1304 performative: "a".into(),
1305 predecessors: vec![NodeRef::Single("begin".into()), NodeRef::Single("b".into())],
1306 successors: vec![],
1307 },
1308 );
1309 let proto = CausalProtocol { steps };
1310 assert!(proto.check_step_uniqueness().is_empty());
1311 }
1312
1313 #[test]
1314 fn test_step_uniqueness_rejects_literal_duplicate_predecessor() {
1315 let mut steps = BTreeMap::new();
1319 steps.insert(
1320 "a".into(),
1321 StepDecl {
1322 performative: "a".into(),
1323 predecessors: vec![
1324 NodeRef::Single("begin".into()),
1325 NodeRef::Single("begin".into()),
1326 ],
1327 successors: vec![],
1328 },
1329 );
1330 let proto = CausalProtocol { steps };
1331 assert!(proto
1332 .check_step_uniqueness()
1333 .iter()
1334 .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
1335 }
1336
1337 #[test]
1338 fn test_step_uniqueness_rejects_literal_duplicate_successor() {
1339 let mut steps = BTreeMap::new();
1346 steps.insert(
1347 "a".into(),
1348 StepDecl {
1349 performative: "a".into(),
1350 predecessors: vec![NodeRef::Single("begin".into())],
1351 successors: vec![NodeRef::Single("b".into()), NodeRef::Single("b".into())],
1352 },
1353 );
1354 let proto = CausalProtocol { steps };
1355 assert!(proto
1356 .check_step_uniqueness()
1357 .iter()
1358 .any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
1359 }
1360
1361 #[test]
1362 fn test_step_uniqueness_accepts_all_fan_in() {
1363 let mut steps = BTreeMap::new();
1365 let mut all_set = BTreeSet::new();
1366 all_set.insert("begin".into());
1367 all_set.insert("x".into());
1368 steps.insert(
1369 "a".into(),
1370 StepDecl {
1371 performative: "a".into(),
1372 predecessors: vec![NodeRef::All(all_set)],
1373 successors: vec![],
1374 },
1375 );
1376 let proto = CausalProtocol { steps };
1377 assert!(proto.check_step_uniqueness().is_empty());
1378 }
1379
1380 #[test]
1383 fn test_verify_r5_protocol_valid() {
1384 let proto = linear_protocol();
1385 let violations = proto.verify_r5_protocol(&["a", "b", "c"]);
1386 assert!(violations.is_empty());
1387 }
1388
1389 #[test]
1390 fn test_verify_r5_protocol_catches_undefined() {
1391 let proto = linear_protocol();
1392 let violations = proto.verify_r5_protocol(&["a"]);
1393 assert!(violations
1394 .iter()
1395 .any(|v| matches!(v, ProtocolViolation::UndefinedPerformative { .. })));
1396 }
1397
1398 #[test]
1399 fn test_verify_r5_protocol_catches_unreachable() {
1400 let mut steps = BTreeMap::new();
1401 steps.insert(
1402 "begin".into(),
1403 StepDecl {
1404 performative: "begin".into(),
1405 predecessors: vec![],
1406 successors: vec![NodeRef::Single("a".into())],
1407 },
1408 );
1409 steps.insert(
1410 "a".into(),
1411 StepDecl {
1412 performative: "a".into(),
1413 predecessors: vec![NodeRef::Single("begin".into())],
1414 successors: vec![],
1415 },
1416 );
1417 steps.insert(
1418 "orphan".into(),
1419 StepDecl {
1420 performative: "orphan".into(),
1421 predecessors: vec![],
1422 successors: vec![],
1423 },
1424 );
1425 let proto = CausalProtocol { steps };
1426 let violations = proto.verify_r5_protocol(&["a", "orphan"]);
1427 assert!(violations
1428 .iter()
1429 .any(|v| matches!(v, ProtocolViolation::Unreachable { step } if step == "orphan")));
1430 }
1431
1432 #[test]
1435 fn test_protocol_violation_display() {
1436 let v = ProtocolViolation::Cycle {
1437 participants: vec!["a".into(), "b".into()],
1438 };
1439 assert_eq!(v.to_string(), "cycle detected: a → b");
1440
1441 let v = ProtocolViolation::Unreachable {
1442 step: "orphan".into(),
1443 };
1444 assert!(v.to_string().contains("unreachable"));
1445
1446 let v = ProtocolViolation::UndefinedPerformative { name: "foo".into() };
1447 assert!(v.to_string().contains("not defined"));
1448
1449 let v = ProtocolViolation::DuplicateStep { name: "bar".into() };
1450 assert!(v.to_string().contains("duplicate"));
1451 }
1452
1453 #[test]
1456 fn test_empty_protocol_passes_all_checks() {
1457 let proto = CausalProtocol {
1458 steps: BTreeMap::new(),
1459 };
1460 assert!(proto.check_acyclicity().is_empty());
1461 assert!(proto.check_reachability().is_empty());
1462 assert!(proto.check_performative_definedness(&[]).is_empty());
1463 assert!(proto.check_step_uniqueness().is_empty());
1464 assert!(proto.verify_r5_protocol(&[]).is_empty());
1465 }
1466
1467 use crate::message::{Message, Performative};
1472 use crate::sexpr::{Atom, SExpr};
1473 use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
1474
1475 fn chash(s: &str) -> ContentHash {
1476 ContentHash(s.into())
1477 }
1478
1479 fn tid(s: &str) -> ThreadId {
1480 ThreadId(s.into())
1481 }
1482
1483 fn make_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
1484 Message::Simple {
1485 performative: Performative::Custom(perf.into()),
1486 recipient: None,
1487 content: SExpr::Atom(Atom::Str("x".into())),
1488 params: alloc::vec![],
1489 thread: None,
1490 sender: None,
1491 caused_by,
1492 }
1493 }
1494
1495 fn verification_protocol() -> CausalProtocol {
1497 let mut steps = BTreeMap::new();
1498 steps.insert(
1499 "begin".into(),
1500 StepDecl {
1501 performative: "begin".into(),
1502 predecessors: vec![],
1503 successors: vec![NodeRef::Single("a".into())],
1504 },
1505 );
1506 steps.insert(
1507 "a".into(),
1508 StepDecl {
1509 performative: "a".into(),
1510 predecessors: vec![NodeRef::Single("begin".into())],
1511 successors: vec![NodeRef::Single("b".into())],
1512 },
1513 );
1514 steps.insert(
1515 "b".into(),
1516 StepDecl {
1517 performative: "b".into(),
1518 predecessors: vec![NodeRef::Single("a".into())],
1519 successors: vec![NodeRef::Single("c".into())],
1520 },
1521 );
1522 steps.insert(
1523 "c".into(),
1524 StepDecl {
1525 performative: "c".into(),
1526 predecessors: vec![NodeRef::Single("b".into())],
1527 successors: vec![],
1528 },
1529 );
1530 CausalProtocol { steps }
1531 }
1532
1533 fn fan_in_protocol() -> CausalProtocol {
1535 let mut steps = BTreeMap::new();
1536 steps.insert(
1537 "begin".into(),
1538 StepDecl {
1539 performative: "begin".into(),
1540 predecessors: vec![],
1541 successors: vec![NodeRef::Single("x".into()), NodeRef::Single("y".into())],
1542 },
1543 );
1544 steps.insert(
1545 "x".into(),
1546 StepDecl {
1547 performative: "x".into(),
1548 predecessors: vec![NodeRef::Single("begin".into())],
1549 successors: vec![],
1550 },
1551 );
1552 steps.insert(
1553 "y".into(),
1554 StepDecl {
1555 performative: "y".into(),
1556 predecessors: vec![NodeRef::Single("begin".into())],
1557 successors: vec![],
1558 },
1559 );
1560 let mut all_set = BTreeSet::new();
1561 all_set.insert("x".into());
1562 all_set.insert("y".into());
1563 steps.insert(
1564 "z".into(),
1565 StepDecl {
1566 performative: "z".into(),
1567 predecessors: vec![NodeRef::All(all_set)],
1568 successors: vec![],
1569 },
1570 );
1571 CausalProtocol { steps }
1572 }
1573
1574 #[test]
1577 fn verify_begin_valid() {
1578 let proto = verification_protocol();
1579 let store = ThreadedMessageStore::new();
1580 let t = tid("t1");
1581 let result = verify_causal("a", Some(&CausedBy::Begin), &store, &proto, &t);
1582 assert_eq!(result, VerificationResult::Valid);
1583 }
1584
1585 #[test]
1586 fn verify_begin_invalid_not_successor_of_begin() {
1587 let proto = verification_protocol();
1588 let store = ThreadedMessageStore::new();
1589 let t = tid("t1");
1590 let result = verify_causal("c", Some(&CausedBy::Begin), &store, &proto, &t);
1592 assert!(matches!(
1593 result,
1594 VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
1595 ));
1596 }
1597
1598 #[test]
1601 fn verify_single_valid() {
1602 let proto = verification_protocol();
1603 let mut store = ThreadedMessageStore::new();
1604 let t = tid("t1");
1605 store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1607 let result = verify_causal(
1609 "b",
1610 Some(&CausedBy::Single("h1".into())),
1611 &store,
1612 &proto,
1613 &t,
1614 );
1615 assert_eq!(result, VerificationResult::Valid);
1616 }
1617
1618 #[test]
1619 fn verify_single_unknown_predecessor_not_in_store() {
1620 let proto = verification_protocol();
1621 let store = ThreadedMessageStore::new();
1622 let t = tid("t1");
1623 let result = verify_causal(
1624 "b",
1625 Some(&CausedBy::Single("missing".into())),
1626 &store,
1627 &proto,
1628 &t,
1629 );
1630 assert_eq!(result, VerificationResult::Unknown);
1631 }
1632
1633 #[test]
1634 fn verify_single_wrong_type() {
1635 let proto = verification_protocol();
1636 let mut store = ThreadedMessageStore::new();
1637 let t = tid("t1");
1638 store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
1640 let result = verify_causal(
1642 "b",
1643 Some(&CausedBy::Single("h1".into())),
1644 &store,
1645 &proto,
1646 &t,
1647 );
1648 assert!(matches!(
1649 result,
1650 VerificationResult::Violation(CausalViolation::InvalidPredecessor {
1651 found,
1652 ..
1653 }) if found == "c"
1654 ));
1655 }
1656
1657 #[test]
1660 fn verify_single_wrong_thread_is_unknown() {
1661 let proto = verification_protocol();
1662 let mut store = ThreadedMessageStore::new();
1663 store.append(chash("h1"), tid("t1"), make_msg("a", Some(CausedBy::Begin)));
1665 let result = verify_causal(
1667 "b",
1668 Some(&CausedBy::Single("h1".into())),
1669 &store,
1670 &proto,
1671 &tid("t2"),
1672 );
1673 assert_eq!(result, VerificationResult::Unknown);
1674 }
1675
1676 #[test]
1679 fn verify_missing_caused_by_violation() {
1680 let proto = verification_protocol();
1681 let store = ThreadedMessageStore::new();
1682 let t = tid("t1");
1683 let result = verify_causal("b", None, &store, &proto, &t);
1685 assert!(matches!(
1686 result,
1687 VerificationResult::Violation(CausalViolation::MissingCausedBy)
1688 ));
1689 }
1690
1691 #[test]
1692 fn verify_missing_caused_by_ok_when_no_predecessors() {
1693 let proto = verification_protocol();
1695 let store = ThreadedMessageStore::new();
1696 let t = tid("t1");
1697 let result = verify_causal("begin", None, &store, &proto, &t);
1698 assert_eq!(result, VerificationResult::Valid);
1699 }
1700
1701 #[test]
1704 fn verify_unknown_performative_is_valid() {
1705 let proto = verification_protocol();
1706 let store = ThreadedMessageStore::new();
1707 let t = tid("t1");
1708 let result = verify_causal(
1709 "not-in-protocol",
1710 Some(&CausedBy::Begin),
1711 &store,
1712 &proto,
1713 &t,
1714 );
1715 assert_eq!(result, VerificationResult::Valid);
1716 }
1717
1718 #[test]
1721 fn verify_fan_in_all_valid() {
1722 let proto = fan_in_protocol();
1723 let mut store = ThreadedMessageStore::new();
1724 let t = tid("t1");
1725 store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1726 store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
1727 let result = verify_causal(
1728 "z",
1729 Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
1730 &store,
1731 &proto,
1732 &t,
1733 );
1734 assert_eq!(result, VerificationResult::Valid);
1735 }
1736
1737 #[test]
1738 fn verify_fan_in_one_unknown() {
1739 let proto = fan_in_protocol();
1740 let mut store = ThreadedMessageStore::new();
1741 let t = tid("t1");
1742 store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1743 let result = verify_causal(
1745 "z",
1746 Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
1747 &store,
1748 &proto,
1749 &t,
1750 );
1751 assert_eq!(result, VerificationResult::Unknown);
1752 }
1753
1754 #[test]
1755 fn verify_fan_in_wrong_type() {
1756 let proto = fan_in_protocol();
1757 let mut store = ThreadedMessageStore::new();
1758 let t = tid("t1");
1759 store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1760 store.append(
1762 chash("hw"),
1763 t.clone(),
1764 make_msg("wrong", Some(CausedBy::Begin)),
1765 );
1766 let result = verify_causal(
1767 "z",
1768 Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hw".into()])),
1769 &store,
1770 &proto,
1771 &t,
1772 );
1773 assert!(matches!(
1774 result,
1775 VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
1776 ));
1777 }
1778
1779 #[test]
1780 fn verify_fan_in_incomplete() {
1781 let proto = fan_in_protocol();
1782 let mut store = ThreadedMessageStore::new();
1783 let t = tid("t1");
1784 store.append(
1786 chash("hx1"),
1787 t.clone(),
1788 make_msg("x", Some(CausedBy::Begin)),
1789 );
1790 store.append(
1791 chash("hx2"),
1792 t.clone(),
1793 make_msg("x", Some(CausedBy::Begin)),
1794 );
1795 let result = verify_causal(
1796 "z",
1797 Some(&CausedBy::Multiple(alloc::vec!["hx1".into(), "hx2".into()])),
1798 &store,
1799 &proto,
1800 &t,
1801 );
1802 assert!(matches!(
1803 result,
1804 VerificationResult::Violation(CausalViolation::IncompleteFanIn { .. })
1805 ));
1806 }
1807
1808 #[test]
1809 fn verify_fan_in_without_all_decl() {
1810 let proto = verification_protocol();
1811 let store = ThreadedMessageStore::new();
1812 let t = tid("t1");
1813 let result = verify_causal(
1815 "b",
1816 Some(&CausedBy::Multiple(alloc::vec!["h1".into(), "h2".into()])),
1817 &store,
1818 &proto,
1819 &t,
1820 );
1821 assert!(matches!(
1822 result,
1823 VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl { .. })
1824 ));
1825 }
1826
1827 #[test]
1830 fn verify_monotone_unknown_to_valid() {
1831 let proto = verification_protocol();
1832 let mut store = ThreadedMessageStore::new();
1833 let t = tid("t1");
1834
1835 let r1 = verify_causal(
1837 "b",
1838 Some(&CausedBy::Single("h1".into())),
1839 &store,
1840 &proto,
1841 &t,
1842 );
1843 assert_eq!(r1, VerificationResult::Unknown);
1844
1845 store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1847
1848 let r2 = verify_causal(
1850 "b",
1851 Some(&CausedBy::Single("h1".into())),
1852 &store,
1853 &proto,
1854 &t,
1855 );
1856 assert_eq!(r2, VerificationResult::Valid);
1857 }
1858
1859 #[test]
1860 fn verify_monotone_unknown_to_violation() {
1861 let proto = verification_protocol();
1862 let mut store = ThreadedMessageStore::new();
1863 let t = tid("t1");
1864
1865 let r1 = verify_causal(
1867 "b",
1868 Some(&CausedBy::Single("h1".into())),
1869 &store,
1870 &proto,
1871 &t,
1872 );
1873 assert_eq!(r1, VerificationResult::Unknown);
1874
1875 store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
1877
1878 let r2 = verify_causal(
1880 "b",
1881 Some(&CausedBy::Single("h1".into())),
1882 &store,
1883 &proto,
1884 &t,
1885 );
1886 assert!(matches!(r2, VerificationResult::Violation(_)));
1887 }
1888
1889 #[test]
1892 fn verify_any_predecessor_either_type_valid() {
1893 let mut steps = BTreeMap::new();
1894 let mut any_set = BTreeSet::new();
1895 any_set.insert("x".into());
1896 any_set.insert("y".into());
1897 steps.insert(
1898 "z".into(),
1899 StepDecl {
1900 performative: "z".into(),
1901 predecessors: vec![NodeRef::Any(any_set)],
1902 successors: vec![],
1903 },
1904 );
1905 let proto = CausalProtocol { steps };
1906 let mut store = ThreadedMessageStore::new();
1907 let t = tid("t1");
1908
1909 store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1911 let r = verify_causal(
1912 "z",
1913 Some(&CausedBy::Single("hx".into())),
1914 &store,
1915 &proto,
1916 &t,
1917 );
1918 assert_eq!(r, VerificationResult::Valid);
1919
1920 store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
1922 let r = verify_causal(
1923 "z",
1924 Some(&CausedBy::Single("hy".into())),
1925 &store,
1926 &proto,
1927 &t,
1928 );
1929 assert_eq!(r, VerificationResult::Valid);
1930 }
1931
1932 #[test]
1935 fn verify_extraneous_predecessor() {
1936 let mut steps = BTreeMap::new();
1937 steps.insert(
1938 "root".into(),
1939 StepDecl {
1940 performative: "root".into(),
1941 predecessors: vec![],
1942 successors: vec![],
1943 },
1944 );
1945 let proto = CausalProtocol { steps };
1946 let mut store = ThreadedMessageStore::new();
1947 let t = tid("t1");
1948 store.append(chash("h1"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
1949 let result = verify_causal(
1951 "root",
1952 Some(&CausedBy::Single("h1".into())),
1953 &store,
1954 &proto,
1955 &t,
1956 );
1957 assert!(matches!(
1958 result,
1959 VerificationResult::Violation(CausalViolation::ExtraneousPredecessor { .. })
1960 ));
1961 }
1962
1963 #[test]
1966 fn verify_is_stateless() {
1967 let proto = verification_protocol();
1968 let mut store = ThreadedMessageStore::new();
1969 let t = tid("t1");
1970 store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
1971
1972 let r1 = verify_causal(
1973 "b",
1974 Some(&CausedBy::Single("h1".into())),
1975 &store,
1976 &proto,
1977 &t,
1978 );
1979 let r2 = verify_causal(
1980 "b",
1981 Some(&CausedBy::Single("h1".into())),
1982 &store,
1983 &proto,
1984 &t,
1985 );
1986 assert_eq!(r1, r2);
1987 }
1988
1989 use crate::attest::{sign_attestation_v2, AttestationHeader};
1994 use crate::envelope::RedactedEnvelope;
1995 use crate::keyid::KeyId;
1996 use crate::r4::Signer;
1997
1998 struct TestSigner {
2001 secret: &'static [u8],
2002 }
2003
2004 impl Signer for TestSigner {
2005 fn sign(&self, data: &[u8]) -> Vec<u8> {
2006 use sha2::{Digest, Sha256};
2007 let mut h = Sha256::new();
2008 h.update(self.secret);
2009 h.update(data);
2010 h.finalize().to_vec()
2011 }
2012 fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
2013 self.sign(data) == sig
2014 }
2015 }
2016
2017 const SIGNER: TestSigner = TestSigner { secret: b"alice" };
2018
2019 fn signed_env(hash: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
2020 let mut to = BTreeSet::new();
2021 to.insert(KeyId::parse("@bob").unwrap());
2022 let header = AttestationHeader {
2023 content_hash: hash.into(),
2024 performative: perf.into(),
2025 from: KeyId::parse("@alice").unwrap(),
2026 to,
2027 thread: thread_name.into(),
2028 caused_by: Some(CausedBy::Begin),
2029 };
2030 let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
2031 RedactedEnvelope { header, signature }
2032 }
2033
2034 #[test]
2039 fn single_reference_resolves_through_an_envelope() {
2040 let proto = verification_protocol();
2041 let mut store = ThreadedMessageStore::new();
2042 let t = tid("t1");
2043 let msg_b = ("b", Some(CausedBy::Single("h1".into())));
2044
2045 assert_eq!(
2047 verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2048 VerificationResult::Unknown
2049 );
2050
2051 store
2053 .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2054 .unwrap();
2055 assert_eq!(
2056 verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2057 VerificationResult::Valid
2058 );
2059
2060 let mut full_store = ThreadedMessageStore::new();
2062 full_store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
2063 assert_eq!(
2064 verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
2065 verify_causal(msg_b.0, msg_b.1.as_ref(), &full_store, &proto, &t),
2066 );
2067 }
2068
2069 #[test]
2073 fn envelope_with_wrong_type_is_the_typed_violation() {
2074 let proto = verification_protocol();
2075 let mut store = ThreadedMessageStore::new();
2076 let t = tid("t1");
2077 store
2078 .append_envelope(signed_env("h1", "c", "t1"), &SIGNER)
2079 .unwrap();
2080 assert_eq!(
2081 verify_causal(
2082 "b",
2083 Some(&CausedBy::Single("h1".into())),
2084 &store,
2085 &proto,
2086 &t
2087 ),
2088 VerificationResult::Violation(CausalViolation::InvalidPredecessor {
2089 caused_by: "h1".into(),
2090 expected: vec!["a".into()],
2091 found: "c".into(),
2092 })
2093 );
2094 }
2095
2096 #[test]
2099 fn envelope_is_scoped_to_its_authenticated_thread() {
2100 let proto = verification_protocol();
2101 let mut store = ThreadedMessageStore::new();
2102 store
2103 .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2104 .unwrap();
2105 assert_eq!(
2106 verify_causal(
2107 "b",
2108 Some(&CausedBy::Single("h1".into())),
2109 &store,
2110 &proto,
2111 &tid("t2")
2112 ),
2113 VerificationResult::Unknown
2114 );
2115 }
2116
2117 #[test]
2121 fn full_message_shadows_its_own_envelope() {
2122 let proto = verification_protocol();
2123 let mut store = ThreadedMessageStore::new();
2124 let t = tid("t1");
2125 store
2126 .append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
2127 .unwrap();
2128 store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
2129 assert_eq!(
2130 verify_causal(
2131 "b",
2132 Some(&CausedBy::Single("h1".into())),
2133 &store,
2134 &proto,
2135 &t
2136 ),
2137 VerificationResult::Valid
2138 );
2139 }
2140
2141 #[test]
2146 fn fan_in_type_check_resolves_through_envelopes() {
2147 let proto = fan_in_protocol();
2148 let mut store = ThreadedMessageStore::new();
2149 let t = tid("t1");
2150 store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
2152 let z = CausedBy::Multiple(vec!["hx".into(), "hy".into()]);
2153 assert_eq!(
2154 verify_causal("z", Some(&z), &store, &proto, &t),
2155 VerificationResult::Unknown
2156 );
2157 store
2158 .append_envelope(signed_env("hy", "y", "t1"), &SIGNER)
2159 .unwrap();
2160 assert_eq!(
2161 verify_causal("z", Some(&z), &store, &proto, &t),
2162 VerificationResult::Valid
2163 );
2164 }
2165
2166 use crate::envelope::{build_opened, OpenedEnvelope, HEADER_FIELDS};
2172 use crate::keyid::SignatureSuite;
2173 use crate::message::Recipients;
2174
2175 fn opened_pred(perf: &str, thread_name: &str) -> (OpenedEnvelope, String) {
2179 let mut to = BTreeSet::new();
2180 to.insert("@bob".to_string());
2181 let m = Message::Simple {
2182 performative: Performative::Custom(perf.into()),
2183 recipient: Some(Recipients::Set(to)),
2184 content: SExpr::Atom(Atom::Str("secret-payload".into())),
2185 params: alloc::vec![],
2186 thread: Some(thread_name.into()),
2187 sender: Some("@alice".into()),
2188 caused_by: Some(CausedBy::Begin),
2189 };
2190 let root = crate::typed_addr::typed_root(&m);
2191 let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
2192 (env, root)
2193 }
2194
2195 #[test]
2200 fn single_reference_resolves_through_an_opened_envelope() {
2201 let proto = verification_protocol();
2202 let mut store = ThreadedMessageStore::new();
2203 let t = tid("t1");
2204 let (env, root) = opened_pred("a", "t1");
2205 let cb = CausedBy::Single(root);
2206
2207 assert_eq!(
2208 verify_causal("b", Some(&cb), &store, &proto, &t),
2209 VerificationResult::Unknown
2210 );
2211 store.append_opened(env, &SIGNER).unwrap();
2212 assert_eq!(
2213 verify_causal("b", Some(&cb), &store, &proto, &t),
2214 VerificationResult::Valid
2215 );
2216 }
2217
2218 #[test]
2222 fn opened_envelope_with_wrong_type_is_the_typed_violation() {
2223 let proto = verification_protocol();
2224 let mut store = ThreadedMessageStore::new();
2225 let t = tid("t1");
2226 let (env, root) = opened_pred("c", "t1"); store.append_opened(env, &SIGNER).unwrap();
2228 assert_eq!(
2229 verify_causal(
2230 "b",
2231 Some(&CausedBy::Single(root.clone())),
2232 &store,
2233 &proto,
2234 &t
2235 ),
2236 VerificationResult::Violation(CausalViolation::InvalidPredecessor {
2237 caused_by: root,
2238 expected: vec!["a".into()],
2239 found: "c".into(),
2240 })
2241 );
2242 }
2243
2244 #[test]
2247 fn opened_envelope_is_scoped_to_its_authenticated_thread() {
2248 let proto = verification_protocol();
2249 let mut store = ThreadedMessageStore::new();
2250 let (env, root) = opened_pred("a", "t1");
2251 store.append_opened(env, &SIGNER).unwrap();
2252 assert_eq!(
2253 verify_causal(
2254 "b",
2255 Some(&CausedBy::Single(root)),
2256 &store,
2257 &proto,
2258 &tid("t2")
2259 ),
2260 VerificationResult::Unknown
2261 );
2262 }
2263
2264 #[test]
2271 fn fan_in_type_check_resolves_through_opened_envelopes() {
2272 let proto = fan_in_protocol();
2273 let mut store = ThreadedMessageStore::new();
2274 let t = tid("t1");
2275 let (env_x, root_x) = opened_pred("x", "t1");
2276 let (env_y, root_y) = opened_pred("y", "t1");
2277 let z = CausedBy::Multiple(vec![root_x.clone(), root_y.clone()]);
2278
2279 store.append_opened(env_x, &SIGNER).unwrap();
2280 assert_eq!(
2281 verify_causal("z", Some(&z), &store, &proto, &t),
2282 VerificationResult::Unknown,
2283 "one member still missing"
2284 );
2285 store.append_opened(env_y, &SIGNER).unwrap();
2286 assert_eq!(
2287 verify_causal("z", Some(&z), &store, &proto, &t),
2288 VerificationResult::Valid
2289 );
2290 }
2291}