#![forbid(unsafe_code)]
use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use crate::causal_kernel::{self as kernel, Decision, FanIn, Lookup};
use crate::message::CausedBy;
use crate::store::{ContentHash, MessageStore, ThreadId};
pub const BEGIN_KEYWORD: &str = "begin";
pub const REPEAT_SEPARATOR: char = '#';
pub fn repeat_base_name(name: &str) -> &str {
match name.find(REPEAT_SEPARATOR) {
Some(idx) => &name[..idx],
None => name,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NodeRef {
Single(String),
Any(BTreeSet<String>),
All(BTreeSet<String>),
}
impl NodeRef {
pub fn performatives(&self) -> impl Iterator<Item = &str> {
match self {
NodeRef::Single(s) => {
let v: Vec<&str> = alloc::vec![s.as_str()];
v.into_iter()
}
NodeRef::Any(set) | NodeRef::All(set) => {
let v: Vec<&str> = set.iter().map(|s| s.as_str()).collect();
v.into_iter()
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StepDecl {
pub performative: String,
pub predecessors: Vec<NodeRef>,
pub successors: Vec<NodeRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CausalProtocol {
pub steps: BTreeMap<String, StepDecl>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProtocolViolation {
Cycle { participants: Vec<String> },
Unreachable { step: String },
UndefinedPerformative { name: String },
DuplicateStep { name: String },
}
impl fmt::Display for ProtocolViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cycle { participants } => {
write!(f, "cycle detected: {}", participants.join(" → "))
}
Self::Unreachable { step } => {
write!(f, "step '{}' is unreachable from begin", step)
}
Self::UndefinedPerformative { name } => {
write!(f, "performative '{}' is not defined", name)
}
Self::DuplicateStep { name } => {
write!(f, "duplicate step declaration for '{}'", name)
}
}
}
}
fn has_duplicate(refs: &[NodeRef]) -> bool {
for i in 0..refs.len() {
for j in (i + 1)..refs.len() {
if refs[i] == refs[j] {
return true;
}
}
}
false
}
impl CausalProtocol {
fn all_referenced_performatives(&self) -> BTreeSet<String> {
let mut names = BTreeSet::new();
for (name, step) in &self.steps {
if name != BEGIN_KEYWORD {
names.insert(name.clone());
}
for nr in step.predecessors.iter().chain(step.successors.iter()) {
for p in nr.performatives() {
if p != BEGIN_KEYWORD {
names.insert(p.into());
}
}
}
}
names
}
fn successor_graph(&self) -> BTreeMap<&str, BTreeSet<&str>> {
let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
for (name, step) in &self.steps {
graph.entry(name.as_str()).or_default();
for nr in &step.successors {
for s in nr.performatives() {
graph.entry(name.as_str()).or_default().insert(s);
graph.entry(s).or_default();
}
}
}
graph
}
pub fn check_acyclicity(&self) -> Vec<ProtocolViolation> {
let graph = self.successor_graph();
let mut color: BTreeMap<&str, u8> = BTreeMap::new();
let mut path: Vec<&str> = Vec::new();
let mut violations = Vec::new();
for &node in graph.keys() {
if *color.get(node).unwrap_or(&0) == 0 {
Self::dfs_cycle(node, &graph, &mut color, &mut path, &mut violations);
}
}
violations
}
fn dfs_cycle<'a>(
node: &'a str,
graph: &BTreeMap<&'a str, BTreeSet<&'a str>>,
color: &mut BTreeMap<&'a str, u8>,
path: &mut Vec<&'a str>,
violations: &mut Vec<ProtocolViolation>,
) {
color.insert(node, 1); path.push(node);
if let Some(neighbors) = graph.get(node) {
for &next in neighbors {
match color.get(next).unwrap_or(&0) {
0 => Self::dfs_cycle(next, graph, color, path, violations),
1 => {
if let Some(pos) = path.iter().position(|&n| n == next) {
let cycle: Vec<String> =
path[pos..].iter().map(|s| String::from(*s)).collect();
violations.push(ProtocolViolation::Cycle {
participants: cycle,
});
}
}
_ => {} }
}
}
path.pop();
color.insert(node, 2); }
pub fn check_reachability(&self) -> Vec<ProtocolViolation> {
let graph = self.successor_graph();
let mut visited: BTreeSet<&str> = BTreeSet::new();
let mut queue: Vec<&str> = Vec::new();
if graph.contains_key(BEGIN_KEYWORD) {
queue.push(BEGIN_KEYWORD);
visited.insert(BEGIN_KEYWORD);
}
while let Some(current) = queue.pop() {
if let Some(neighbors) = graph.get(current) {
for &next in neighbors {
if visited.insert(next) {
queue.push(next);
}
}
}
}
let mut violations = Vec::new();
for name in self.steps.keys() {
if name != BEGIN_KEYWORD && !visited.contains(name.as_str()) {
violations.push(ProtocolViolation::Unreachable { step: name.clone() });
}
}
violations
}
pub fn check_performative_definedness(
&self,
defined_performatives: &[&str],
) -> Vec<ProtocolViolation> {
let defined: BTreeSet<&str> = defined_performatives.iter().copied().collect();
let referenced = self.all_referenced_performatives();
let mut flagged: BTreeSet<&str> = BTreeSet::new();
let mut violations = Vec::new();
for name in &referenced {
let base = repeat_base_name(name);
if !defined.contains(base) && flagged.insert(base) {
violations.push(ProtocolViolation::UndefinedPerformative {
name: String::from(base),
});
}
}
violations
}
pub fn expansion_size(&self) -> u32 {
let n = self
.steps
.keys()
.filter(|name| name.as_str() != BEGIN_KEYWORD)
.count();
u32::try_from(n).unwrap_or(u32::MAX)
}
pub fn check_step_uniqueness(&self) -> Vec<ProtocolViolation> {
let mut violations = Vec::new();
for (name, step) in &self.steps {
if has_duplicate(&step.predecessors) || has_duplicate(&step.successors) {
violations.push(ProtocolViolation::DuplicateStep { name: name.clone() });
}
}
violations
}
pub fn verify_r5_protocol(&self, defined_performatives: &[&str]) -> Vec<ProtocolViolation> {
let mut violations = Vec::new();
violations.extend(self.check_step_uniqueness());
violations.extend(self.check_acyclicity());
violations.extend(self.check_reachability());
violations.extend(self.check_performative_definedness(defined_performatives));
violations
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CausalViolation {
UnknownPredecessor { caused_by: String },
InvalidPredecessor {
caused_by: String,
expected: Vec<String>,
found: String,
},
MissingCausedBy,
IncompleteFanIn { missing_types: Vec<String> },
ExtraneousPredecessor { caused_by: String, found: String },
FanInWithoutAllDecl { performative: String },
RoleConformance { reason: String },
}
impl fmt::Display for CausalViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownPredecessor { caused_by } => {
write!(f, "unknown predecessor: {caused_by}")
}
Self::InvalidPredecessor {
caused_by,
expected,
found,
} => {
write!(
f,
"invalid predecessor {caused_by}: expected one of [{}], found {found}",
expected.join(", ")
)
}
Self::MissingCausedBy => write!(f, "missing :caused-by"),
Self::IncompleteFanIn { missing_types } => {
write!(
f,
"incomplete fan-in: missing types [{}]",
missing_types.join(", ")
)
}
Self::ExtraneousPredecessor { caused_by, found } => {
write!(f, "extraneous predecessor {caused_by}: found {found}")
}
Self::FanInWithoutAllDecl { performative } => {
write!(f, "fan-in without (all ...) declaration for {performative}")
}
Self::RoleConformance { reason } => {
write!(f, "role conformance: {reason}")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VerificationResult {
Unknown,
Valid,
Violation(CausalViolation),
}
impl VerificationResult {
pub fn meet(self, other: VerificationResult) -> VerificationResult {
match (&self, &other) {
(VerificationResult::Violation(_), _) => self,
(_, VerificationResult::Violation(_)) => other,
(VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
VerificationResult::Unknown
}
(VerificationResult::Valid, VerificationResult::Valid) => VerificationResult::Valid,
}
}
pub fn join(self, other: VerificationResult) -> VerificationResult {
match (&self, &other) {
(VerificationResult::Valid, _) | (_, VerificationResult::Valid) => {
VerificationResult::Valid
}
(VerificationResult::Unknown, _) | (_, VerificationResult::Unknown) => {
VerificationResult::Unknown
}
(VerificationResult::Violation(_), VerificationResult::Violation(_)) => self,
}
}
pub fn is_resolved(&self) -> bool {
!matches!(self, VerificationResult::Unknown)
}
pub fn is_stable(&self) -> bool {
self.is_resolved()
}
}
impl PartialOrd for VerificationResult {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
use core::cmp::Ordering;
match (self, other) {
(VerificationResult::Unknown, VerificationResult::Unknown) => Some(Ordering::Equal),
(VerificationResult::Valid, VerificationResult::Valid) => Some(Ordering::Equal),
(VerificationResult::Violation(_), VerificationResult::Violation(_)) => {
Some(Ordering::Equal)
}
(VerificationResult::Unknown, _) => Some(Ordering::Less),
(_, VerificationResult::Unknown) => Some(Ordering::Greater),
(VerificationResult::Valid, VerificationResult::Violation(_))
| (VerificationResult::Violation(_), VerificationResult::Valid) => None,
}
}
}
pub(crate) fn predecessor_type<'a, S: MessageStore>(
store: &'a S,
hash: &ContentHash,
thread: &ThreadId,
) -> Option<&'a str> {
if let Some(predecessor_msg) = store.lookup_in_thread(hash, thread) {
return Some(
predecessor_msg
.innermost_simple()
.and_then(|m| m.performative())
.map(|p| p.name())
.unwrap_or(""),
);
}
if let Some(e) = store.envelope_in_thread(hash, thread) {
return Some(e.performative());
}
store
.opened_in_thread(hash, thread)
.and_then(|e| e.performative())
}
pub(crate) fn allowed_single_predecessors(step: &StepDecl) -> Vec<String> {
let mut types = Vec::new();
for nr in &step.predecessors {
match nr {
NodeRef::Single(s) => types.push(s.clone()),
NodeRef::Any(set) => types.extend(set.iter().cloned()),
NodeRef::All(_) => {} }
}
types
}
pub fn verify_causal<S: MessageStore>(
msg_performative: &str,
caused_by: Option<&CausedBy>,
store: &S,
protocol: &CausalProtocol,
thread: &ThreadId,
) -> VerificationResult {
if crate::repeat::has_repeat(protocol) {
return crate::repeat::verify(msg_performative, caused_by, store, protocol, thread, None);
}
let step = match protocol.steps.get(msg_performative) {
Some(s) => s,
None => return VerificationResult::Valid,
};
let has_predecessors = !step.predecessors.is_empty();
match caused_by {
None => match kernel::absent(has_predecessors) {
Decision::Valid => VerificationResult::Valid,
Decision::MissingCausedBy => {
VerificationResult::Violation(CausalViolation::MissingCausedBy)
}
_ => unreachable!("absent decision"),
},
Some(CausedBy::Begin) => {
let begin_allowed = step.predecessors.iter().any(|nr| match nr {
NodeRef::Single(s) => s == BEGIN_KEYWORD,
NodeRef::Any(set) => set.contains(BEGIN_KEYWORD),
NodeRef::All(_) => false,
});
match kernel::literal_begin(begin_allowed) {
Decision::Valid => VerificationResult::Valid,
Decision::InvalidPredecessor => {
VerificationResult::Violation(CausalViolation::InvalidPredecessor {
caused_by: BEGIN_KEYWORD.into(),
expected: allowed_single_predecessors(step),
found: BEGIN_KEYWORD.into(),
})
}
_ => unreachable!("literal-begin decision"),
}
}
Some(CausedBy::Single(hash_str)) => {
let content_hash = ContentHash(hash_str.clone());
let pred_perf = predecessor_type(store, &content_hash, thread);
let allowed = if pred_perf.is_some() {
allowed_single_predecessors(step)
} else {
Vec::new()
};
let lookup = match pred_perf {
None => Lookup::Missing,
Some(p) if allowed.iter().any(|a| a == p) => Lookup::Allowed,
Some(_) => Lookup::Wrong,
};
match kernel::single(has_predecessors, lookup) {
Decision::Valid => VerificationResult::Valid,
Decision::Unknown => VerificationResult::Unknown,
Decision::ExtraneousPredecessor => {
VerificationResult::Violation(CausalViolation::ExtraneousPredecessor {
caused_by: hash_str.clone(),
found: pred_perf.expect("wrong lookup has a type").into(),
})
}
Decision::InvalidPredecessor => {
VerificationResult::Violation(CausalViolation::InvalidPredecessor {
caused_by: hash_str.clone(),
expected: allowed,
found: pred_perf.expect("wrong lookup has a type").into(),
})
}
_ => unreachable!("single decision"),
}
}
Some(CausedBy::Multiple(hashes)) => {
let all_decl = step.predecessors.iter().find_map(|nr| match nr {
NodeRef::All(set) => Some(set),
_ => None,
});
let mut state = FanIn::Clear;
let mut found_types = BTreeSet::new();
let mut first_error = None;
let mut missing = Vec::new();
if let Some(all_set) = all_decl {
for hash_str in hashes {
let content_hash = ContentHash(hash_str.clone());
let lookup = match predecessor_type(store, &content_hash, thread) {
None => Lookup::Missing,
Some(pred_perf) if all_set.contains(pred_perf) => {
found_types.insert(String::from(pred_perf));
Lookup::Allowed
}
Some(pred_perf) => {
if first_error.is_none() {
first_error = Some(CausalViolation::InvalidPredecessor {
caused_by: hash_str.clone(),
expected: all_set.iter().cloned().collect(),
found: pred_perf.into(),
});
}
Lookup::Wrong
}
};
state = kernel::observe(state, lookup);
}
if matches!(state, FanIn::Clear) {
missing = all_set
.iter()
.filter(|t| !found_types.contains(*t))
.cloned()
.collect();
}
}
match kernel::finish(all_decl.is_some(), state, missing.is_empty()) {
Decision::Valid => VerificationResult::Valid,
Decision::Unknown => VerificationResult::Unknown,
Decision::InvalidPredecessor => VerificationResult::Violation(
first_error.expect("wrong fan-in has a diagnostic"),
),
Decision::IncompleteFanIn => {
VerificationResult::Violation(CausalViolation::IncompleteFanIn {
missing_types: missing,
})
}
Decision::FanInWithoutAllDecl => {
VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl {
performative: msg_performative.into(),
})
}
_ => unreachable!("fan-in decision"),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reserved_keyword_vocabulary_is_singleton() {
assert_eq!(BEGIN_KEYWORD, "begin");
}
fn violation() -> VerificationResult {
VerificationResult::Violation(CausalViolation::MissingCausedBy)
}
fn violation2() -> VerificationResult {
VerificationResult::Violation(CausalViolation::UnknownPredecessor {
caused_by: "f1220test".into(),
})
}
#[test]
fn test_construction_unknown() {
let r = VerificationResult::Unknown;
assert!(!r.is_resolved());
assert!(!r.is_stable());
}
#[test]
fn test_construction_valid() {
let r = VerificationResult::Valid;
assert!(r.is_resolved());
assert!(r.is_stable());
}
#[test]
fn test_construction_violation() {
let r = violation();
assert!(r.is_resolved());
assert!(r.is_stable());
}
#[test]
fn test_partial_ord_unknown_lt_valid() {
assert!(VerificationResult::Unknown < VerificationResult::Valid);
}
#[test]
fn test_partial_ord_unknown_lt_violation() {
assert!(VerificationResult::Unknown < violation());
}
#[test]
fn test_partial_ord_valid_violation_incomparable() {
let v = VerificationResult::Valid;
let viol = violation();
assert!(v.partial_cmp(&viol).is_none());
assert!(viol.partial_cmp(&v).is_none());
}
#[test]
fn test_partial_ord_reflexive() {
assert_eq!(
VerificationResult::Unknown.partial_cmp(&VerificationResult::Unknown),
Some(core::cmp::Ordering::Equal)
);
assert_eq!(
VerificationResult::Valid.partial_cmp(&VerificationResult::Valid),
Some(core::cmp::Ordering::Equal)
);
assert_eq!(
violation().partial_cmp(&violation()),
Some(core::cmp::Ordering::Equal)
);
}
#[test]
fn test_meet_unknown_unknown() {
assert_eq!(
VerificationResult::Unknown.meet(VerificationResult::Unknown),
VerificationResult::Unknown
);
}
#[test]
fn test_meet_unknown_valid() {
assert_eq!(
VerificationResult::Unknown.meet(VerificationResult::Valid),
VerificationResult::Unknown
);
}
#[test]
fn test_meet_unknown_violation() {
let result = VerificationResult::Unknown.meet(violation());
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_meet_valid_unknown() {
assert_eq!(
VerificationResult::Valid.meet(VerificationResult::Unknown),
VerificationResult::Unknown
);
}
#[test]
fn test_meet_valid_valid() {
assert_eq!(
VerificationResult::Valid.meet(VerificationResult::Valid),
VerificationResult::Valid
);
}
#[test]
fn test_meet_valid_violation() {
let result = VerificationResult::Valid.meet(violation());
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_meet_violation_unknown() {
let result = violation().meet(VerificationResult::Unknown);
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_meet_violation_valid() {
let result = violation().meet(VerificationResult::Valid);
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_meet_violation_violation() {
let result = violation().meet(violation2());
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_join_unknown_unknown() {
assert_eq!(
VerificationResult::Unknown.join(VerificationResult::Unknown),
VerificationResult::Unknown
);
}
#[test]
fn test_join_unknown_valid() {
assert_eq!(
VerificationResult::Unknown.join(VerificationResult::Valid),
VerificationResult::Valid
);
}
#[test]
fn test_join_unknown_violation() {
let result = VerificationResult::Unknown.join(violation());
assert_eq!(result, VerificationResult::Unknown);
}
#[test]
fn test_join_valid_unknown() {
assert_eq!(
VerificationResult::Valid.join(VerificationResult::Unknown),
VerificationResult::Valid
);
}
#[test]
fn test_join_valid_valid() {
assert_eq!(
VerificationResult::Valid.join(VerificationResult::Valid),
VerificationResult::Valid
);
}
#[test]
fn test_join_valid_violation() {
assert_eq!(
VerificationResult::Valid.join(violation()),
VerificationResult::Valid
);
}
#[test]
fn test_join_violation_unknown() {
let result = violation().join(VerificationResult::Unknown);
assert_eq!(result, VerificationResult::Unknown);
}
#[test]
fn test_join_violation_valid() {
assert_eq!(
violation().join(VerificationResult::Valid),
VerificationResult::Valid
);
}
#[test]
fn test_join_violation_violation() {
let result = violation().join(violation2());
assert!(matches!(result, VerificationResult::Violation(_)));
}
#[test]
fn test_causal_violation_display() {
let v = CausalViolation::MissingCausedBy;
assert_eq!(v.to_string(), "missing :caused-by");
let v = CausalViolation::UnknownPredecessor {
caused_by: "f1220abc".into(),
};
assert_eq!(v.to_string(), "unknown predecessor: f1220abc");
}
#[test]
fn test_causal_violation_variants_exist() {
let _ = CausalViolation::UnknownPredecessor {
caused_by: "h".into(),
};
let _ = CausalViolation::InvalidPredecessor {
caused_by: "h".into(),
expected: vec!["a".into()],
found: "b".into(),
};
let _ = CausalViolation::MissingCausedBy;
let _ = CausalViolation::IncompleteFanIn {
missing_types: vec!["a".into()],
};
let _ = CausalViolation::ExtraneousPredecessor {
caused_by: "h".into(),
found: "x".into(),
};
let _ = CausalViolation::FanInWithoutAllDecl {
performative: "p".into(),
};
}
#[test]
fn test_meet_preserves_first_violation() {
let v1 = violation();
let v2 = violation2();
let result = v1.meet(v2);
assert_eq!(
result,
VerificationResult::Violation(CausalViolation::MissingCausedBy)
);
}
#[test]
fn test_join_preserves_first_violation() {
let v1 = violation();
let result = v1.join(violation2());
assert_eq!(
result,
VerificationResult::Violation(CausalViolation::MissingCausedBy)
);
}
fn linear_protocol() -> CausalProtocol {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![NodeRef::Single("b".into())],
},
);
steps.insert(
"b".into(),
StepDecl {
performative: "b".into(),
predecessors: vec![NodeRef::Single("a".into())],
successors: vec![NodeRef::Single("c".into())],
},
);
steps.insert(
"c".into(),
StepDecl {
performative: "c".into(),
predecessors: vec![NodeRef::Single("b".into())],
successors: vec![],
},
);
CausalProtocol { steps }
}
#[test]
fn test_acyclicity_linear_chain_passes() {
let proto = linear_protocol();
assert!(proto.check_acyclicity().is_empty());
}
#[test]
fn test_acyclicity_direct_cycle_rejected() {
let mut steps = BTreeMap::new();
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("b".into())],
successors: vec![NodeRef::Single("b".into())],
},
);
steps.insert(
"b".into(),
StepDecl {
performative: "b".into(),
predecessors: vec![NodeRef::Single("a".into())],
successors: vec![NodeRef::Single("a".into())],
},
);
let proto = CausalProtocol { steps };
let violations = proto.check_acyclicity();
assert!(!violations.is_empty());
assert!(violations
.iter()
.any(|v| matches!(v, ProtocolViolation::Cycle { .. })));
}
#[test]
fn test_acyclicity_transitive_cycle_rejected() {
let mut steps = BTreeMap::new();
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("c".into())],
successors: vec![NodeRef::Single("b".into())],
},
);
steps.insert(
"b".into(),
StepDecl {
performative: "b".into(),
predecessors: vec![NodeRef::Single("a".into())],
successors: vec![NodeRef::Single("c".into())],
},
);
steps.insert(
"c".into(),
StepDecl {
performative: "c".into(),
predecessors: vec![NodeRef::Single("b".into())],
successors: vec![NodeRef::Single("a".into())],
},
);
let proto = CausalProtocol { steps };
let violations = proto.check_acyclicity();
assert!(!violations.is_empty());
}
#[test]
fn test_reachability_linear_chain_passes() {
let proto = linear_protocol();
assert!(proto.check_reachability().is_empty());
}
#[test]
fn test_reachability_both_from_begin_passes() {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into()), NodeRef::Single("b".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
steps.insert(
"b".into(),
StepDecl {
performative: "b".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
assert!(proto.check_reachability().is_empty());
}
#[test]
fn test_reachability_unreachable_step_rejected() {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
steps.insert(
"c".into(),
StepDecl {
performative: "c".into(),
predecessors: vec![NodeRef::Single("x".into())],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
let violations = proto.check_reachability();
assert_eq!(violations.len(), 1);
assert!(matches!(
&violations[0],
ProtocolViolation::Unreachable { step } if step == "c"
));
}
#[test]
fn test_definedness_all_defined_passes() {
let proto = linear_protocol();
let violations = proto.check_performative_definedness(&["a", "b", "c"]);
assert!(violations.is_empty());
}
#[test]
fn test_definedness_undefined_rejected() {
let proto = linear_protocol();
let violations = proto.check_performative_definedness(&["a"]);
assert_eq!(violations.len(), 2);
let names: Vec<&str> = violations
.iter()
.filter_map(|v| match v {
ProtocolViolation::UndefinedPerformative { name } => Some(name.as_str()),
_ => None,
})
.collect();
assert!(names.contains(&"b"));
assert!(names.contains(&"c"));
}
#[test]
fn test_step_uniqueness_clean_protocol_passes() {
let proto = linear_protocol();
assert!(proto.check_step_uniqueness().is_empty());
}
#[test]
fn test_step_uniqueness_detects_duplicate_successor() {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into()), NodeRef::Single("a".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![
NodeRef::Single("begin".into()),
NodeRef::Single("begin".into()),
],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
let violations = proto.check_step_uniqueness();
let names: BTreeSet<&str> = violations
.iter()
.filter_map(|v| match v {
ProtocolViolation::DuplicateStep { name } => Some(name.as_str()),
_ => None,
})
.collect();
assert!(names.contains("begin"));
assert!(names.contains("a"));
}
#[test]
fn test_step_uniqueness_accepts_distinct_alternatives() {
let mut steps = BTreeMap::new();
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into()), NodeRef::Single("b".into())],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
assert!(proto.check_step_uniqueness().is_empty());
}
#[test]
fn test_step_uniqueness_rejects_literal_duplicate_predecessor() {
let mut steps = BTreeMap::new();
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![
NodeRef::Single("begin".into()),
NodeRef::Single("begin".into()),
],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
assert!(proto
.check_step_uniqueness()
.iter()
.any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
}
#[test]
fn test_step_uniqueness_rejects_literal_duplicate_successor() {
let mut steps = BTreeMap::new();
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![NodeRef::Single("b".into()), NodeRef::Single("b".into())],
},
);
let proto = CausalProtocol { steps };
assert!(proto
.check_step_uniqueness()
.iter()
.any(|v| matches!(v, ProtocolViolation::DuplicateStep { name } if name == "a")));
}
#[test]
fn test_step_uniqueness_accepts_all_fan_in() {
let mut steps = BTreeMap::new();
let mut all_set = BTreeSet::new();
all_set.insert("begin".into());
all_set.insert("x".into());
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::All(all_set)],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
assert!(proto.check_step_uniqueness().is_empty());
}
#[test]
fn test_verify_r5_protocol_valid() {
let proto = linear_protocol();
let violations = proto.verify_r5_protocol(&["a", "b", "c"]);
assert!(violations.is_empty());
}
#[test]
fn test_verify_r5_protocol_catches_undefined() {
let proto = linear_protocol();
let violations = proto.verify_r5_protocol(&["a"]);
assert!(violations
.iter()
.any(|v| matches!(v, ProtocolViolation::UndefinedPerformative { .. })));
}
#[test]
fn test_verify_r5_protocol_catches_unreachable() {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
steps.insert(
"orphan".into(),
StepDecl {
performative: "orphan".into(),
predecessors: vec![],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
let violations = proto.verify_r5_protocol(&["a", "orphan"]);
assert!(violations
.iter()
.any(|v| matches!(v, ProtocolViolation::Unreachable { step } if step == "orphan")));
}
#[test]
fn test_protocol_violation_display() {
let v = ProtocolViolation::Cycle {
participants: vec!["a".into(), "b".into()],
};
assert_eq!(v.to_string(), "cycle detected: a → b");
let v = ProtocolViolation::Unreachable {
step: "orphan".into(),
};
assert!(v.to_string().contains("unreachable"));
let v = ProtocolViolation::UndefinedPerformative { name: "foo".into() };
assert!(v.to_string().contains("not defined"));
let v = ProtocolViolation::DuplicateStep { name: "bar".into() };
assert!(v.to_string().contains("duplicate"));
}
#[test]
fn test_empty_protocol_passes_all_checks() {
let proto = CausalProtocol {
steps: BTreeMap::new(),
};
assert!(proto.check_acyclicity().is_empty());
assert!(proto.check_reachability().is_empty());
assert!(proto.check_performative_definedness(&[]).is_empty());
assert!(proto.check_step_uniqueness().is_empty());
assert!(proto.verify_r5_protocol(&[]).is_empty());
}
use crate::message::{Message, Performative};
use crate::sexpr::{Atom, SExpr};
use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
fn chash(s: &str) -> ContentHash {
ContentHash(s.into())
}
fn tid(s: &str) -> ThreadId {
ThreadId(s.into())
}
fn make_msg(perf: &str, caused_by: Option<CausedBy>) -> Message {
Message::Simple {
performative: Performative::Custom(perf.into()),
recipient: None,
content: SExpr::Atom(Atom::Str("x".into())),
params: alloc::vec![],
thread: None,
sender: None,
caused_by,
}
}
fn verification_protocol() -> CausalProtocol {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("a".into())],
},
);
steps.insert(
"a".into(),
StepDecl {
performative: "a".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![NodeRef::Single("b".into())],
},
);
steps.insert(
"b".into(),
StepDecl {
performative: "b".into(),
predecessors: vec![NodeRef::Single("a".into())],
successors: vec![NodeRef::Single("c".into())],
},
);
steps.insert(
"c".into(),
StepDecl {
performative: "c".into(),
predecessors: vec![NodeRef::Single("b".into())],
successors: vec![],
},
);
CausalProtocol { steps }
}
fn fan_in_protocol() -> CausalProtocol {
let mut steps = BTreeMap::new();
steps.insert(
"begin".into(),
StepDecl {
performative: "begin".into(),
predecessors: vec![],
successors: vec![NodeRef::Single("x".into()), NodeRef::Single("y".into())],
},
);
steps.insert(
"x".into(),
StepDecl {
performative: "x".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
steps.insert(
"y".into(),
StepDecl {
performative: "y".into(),
predecessors: vec![NodeRef::Single("begin".into())],
successors: vec![],
},
);
let mut all_set = BTreeSet::new();
all_set.insert("x".into());
all_set.insert("y".into());
steps.insert(
"z".into(),
StepDecl {
performative: "z".into(),
predecessors: vec![NodeRef::All(all_set)],
successors: vec![],
},
);
CausalProtocol { steps }
}
#[test]
fn verify_begin_valid() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal("a", Some(&CausedBy::Begin), &store, &proto, &t);
assert_eq!(result, VerificationResult::Valid);
}
#[test]
fn verify_begin_invalid_not_successor_of_begin() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal("c", Some(&CausedBy::Begin), &store, &proto, &t);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
));
}
#[test]
fn verify_single_valid() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
let result = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert_eq!(result, VerificationResult::Valid);
}
#[test]
fn verify_single_unknown_predecessor_not_in_store() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal(
"b",
Some(&CausedBy::Single("missing".into())),
&store,
&proto,
&t,
);
assert_eq!(result, VerificationResult::Unknown);
}
#[test]
fn verify_single_wrong_type() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
let result = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::InvalidPredecessor {
found,
..
}) if found == "c"
));
}
#[test]
fn verify_single_wrong_thread_is_unknown() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
store.append(chash("h1"), tid("t1"), make_msg("a", Some(CausedBy::Begin)));
let result = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&tid("t2"),
);
assert_eq!(result, VerificationResult::Unknown);
}
#[test]
fn verify_missing_caused_by_violation() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal("b", None, &store, &proto, &t);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::MissingCausedBy)
));
}
#[test]
fn verify_missing_caused_by_ok_when_no_predecessors() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal("begin", None, &store, &proto, &t);
assert_eq!(result, VerificationResult::Valid);
}
#[test]
fn verify_unknown_performative_is_valid() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal(
"not-in-protocol",
Some(&CausedBy::Begin),
&store,
&proto,
&t,
);
assert_eq!(result, VerificationResult::Valid);
}
#[test]
fn verify_fan_in_all_valid() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
let result = verify_causal(
"z",
Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
&store,
&proto,
&t,
);
assert_eq!(result, VerificationResult::Valid);
}
#[test]
fn verify_fan_in_one_unknown() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
let result = verify_causal(
"z",
Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hy".into()])),
&store,
&proto,
&t,
);
assert_eq!(result, VerificationResult::Unknown);
}
#[test]
fn verify_fan_in_wrong_type() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
store.append(
chash("hw"),
t.clone(),
make_msg("wrong", Some(CausedBy::Begin)),
);
let result = verify_causal(
"z",
Some(&CausedBy::Multiple(alloc::vec!["hx".into(), "hw".into()])),
&store,
&proto,
&t,
);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::InvalidPredecessor { .. })
));
}
#[test]
fn verify_fan_in_incomplete() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(
chash("hx1"),
t.clone(),
make_msg("x", Some(CausedBy::Begin)),
);
store.append(
chash("hx2"),
t.clone(),
make_msg("x", Some(CausedBy::Begin)),
);
let result = verify_causal(
"z",
Some(&CausedBy::Multiple(alloc::vec!["hx1".into(), "hx2".into()])),
&store,
&proto,
&t,
);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::IncompleteFanIn { .. })
));
}
#[test]
fn verify_fan_in_without_all_decl() {
let proto = verification_protocol();
let store = ThreadedMessageStore::new();
let t = tid("t1");
let result = verify_causal(
"b",
Some(&CausedBy::Multiple(alloc::vec!["h1".into(), "h2".into()])),
&store,
&proto,
&t,
);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl { .. })
));
}
#[test]
fn verify_monotone_unknown_to_valid() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let r1 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert_eq!(r1, VerificationResult::Unknown);
store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
let r2 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert_eq!(r2, VerificationResult::Valid);
}
#[test]
fn verify_monotone_unknown_to_violation() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let r1 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert_eq!(r1, VerificationResult::Unknown);
store.append(chash("h1"), t.clone(), make_msg("c", Some(CausedBy::Begin)));
let r2 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert!(matches!(r2, VerificationResult::Violation(_)));
}
#[test]
fn verify_any_predecessor_either_type_valid() {
let mut steps = BTreeMap::new();
let mut any_set = BTreeSet::new();
any_set.insert("x".into());
any_set.insert("y".into());
steps.insert(
"z".into(),
StepDecl {
performative: "z".into(),
predecessors: vec![NodeRef::Any(any_set)],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
let r = verify_causal(
"z",
Some(&CausedBy::Single("hx".into())),
&store,
&proto,
&t,
);
assert_eq!(r, VerificationResult::Valid);
store.append(chash("hy"), t.clone(), make_msg("y", Some(CausedBy::Begin)));
let r = verify_causal(
"z",
Some(&CausedBy::Single("hy".into())),
&store,
&proto,
&t,
);
assert_eq!(r, VerificationResult::Valid);
}
#[test]
fn verify_extraneous_predecessor() {
let mut steps = BTreeMap::new();
steps.insert(
"root".into(),
StepDecl {
performative: "root".into(),
predecessors: vec![],
successors: vec![],
},
);
let proto = CausalProtocol { steps };
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("h1"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
let result = verify_causal(
"root",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert!(matches!(
result,
VerificationResult::Violation(CausalViolation::ExtraneousPredecessor { .. })
));
}
#[test]
fn verify_is_stateless() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
let r1 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
let r2 = verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t,
);
assert_eq!(r1, r2);
}
use crate::attest::{sign_attestation_v2, AttestationHeader};
use crate::envelope::RedactedEnvelope;
use crate::keyid::KeyId;
use crate::r4::Signer;
struct TestSigner {
secret: &'static [u8],
}
impl Signer for TestSigner {
fn sign(&self, data: &[u8]) -> Vec<u8> {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(self.secret);
h.update(data);
h.finalize().to_vec()
}
fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
self.sign(data) == sig
}
}
const SIGNER: TestSigner = TestSigner { secret: b"alice" };
fn signed_env(hash: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
let mut to = BTreeSet::new();
to.insert(KeyId::parse("@bob").unwrap());
let header = AttestationHeader {
content_hash: hash.into(),
performative: perf.into(),
from: KeyId::parse("@alice").unwrap(),
to,
thread: thread_name.into(),
caused_by: Some(CausedBy::Begin),
};
let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
RedactedEnvelope { header, signature }
}
#[test]
fn single_reference_resolves_through_an_envelope() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let msg_b = ("b", Some(CausedBy::Single("h1".into())));
assert_eq!(
verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
VerificationResult::Unknown
);
store
.append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
.unwrap();
assert_eq!(
verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
VerificationResult::Valid
);
let mut full_store = ThreadedMessageStore::new();
full_store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
assert_eq!(
verify_causal(msg_b.0, msg_b.1.as_ref(), &store, &proto, &t),
verify_causal(msg_b.0, msg_b.1.as_ref(), &full_store, &proto, &t),
);
}
#[test]
fn envelope_with_wrong_type_is_the_typed_violation() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store
.append_envelope(signed_env("h1", "c", "t1"), &SIGNER)
.unwrap();
assert_eq!(
verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t
),
VerificationResult::Violation(CausalViolation::InvalidPredecessor {
caused_by: "h1".into(),
expected: vec!["a".into()],
found: "c".into(),
})
);
}
#[test]
fn envelope_is_scoped_to_its_authenticated_thread() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
store
.append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
.unwrap();
assert_eq!(
verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&tid("t2")
),
VerificationResult::Unknown
);
}
#[test]
fn full_message_shadows_its_own_envelope() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store
.append_envelope(signed_env("h1", "a", "t1"), &SIGNER)
.unwrap();
store.append(chash("h1"), t.clone(), make_msg("a", Some(CausedBy::Begin)));
assert_eq!(
verify_causal(
"b",
Some(&CausedBy::Single("h1".into())),
&store,
&proto,
&t
),
VerificationResult::Valid
);
}
#[test]
fn fan_in_type_check_resolves_through_envelopes() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
store.append(chash("hx"), t.clone(), make_msg("x", Some(CausedBy::Begin)));
let z = CausedBy::Multiple(vec!["hx".into(), "hy".into()]);
assert_eq!(
verify_causal("z", Some(&z), &store, &proto, &t),
VerificationResult::Unknown
);
store
.append_envelope(signed_env("hy", "y", "t1"), &SIGNER)
.unwrap();
assert_eq!(
verify_causal("z", Some(&z), &store, &proto, &t),
VerificationResult::Valid
);
}
use crate::envelope::{build_opened, OpenedEnvelope, HEADER_FIELDS};
use crate::keyid::SignatureSuite;
use crate::message::Recipients;
fn opened_pred(perf: &str, thread_name: &str) -> (OpenedEnvelope, String) {
let mut to = BTreeSet::new();
to.insert("@bob".to_string());
let m = Message::Simple {
performative: Performative::Custom(perf.into()),
recipient: Some(Recipients::Set(to)),
content: SExpr::Atom(Atom::Str("secret-payload".into())),
params: alloc::vec![],
thread: Some(thread_name.into()),
sender: Some("@alice".into()),
caused_by: Some(CausedBy::Begin),
};
let root = crate::typed_addr::typed_root(&m);
let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
(env, root)
}
#[test]
fn single_reference_resolves_through_an_opened_envelope() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let (env, root) = opened_pred("a", "t1");
let cb = CausedBy::Single(root);
assert_eq!(
verify_causal("b", Some(&cb), &store, &proto, &t),
VerificationResult::Unknown
);
store.append_opened(env, &SIGNER).unwrap();
assert_eq!(
verify_causal("b", Some(&cb), &store, &proto, &t),
VerificationResult::Valid
);
}
#[test]
fn opened_envelope_with_wrong_type_is_the_typed_violation() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let (env, root) = opened_pred("c", "t1"); store.append_opened(env, &SIGNER).unwrap();
assert_eq!(
verify_causal(
"b",
Some(&CausedBy::Single(root.clone())),
&store,
&proto,
&t
),
VerificationResult::Violation(CausalViolation::InvalidPredecessor {
caused_by: root,
expected: vec!["a".into()],
found: "c".into(),
})
);
}
#[test]
fn opened_envelope_is_scoped_to_its_authenticated_thread() {
let proto = verification_protocol();
let mut store = ThreadedMessageStore::new();
let (env, root) = opened_pred("a", "t1");
store.append_opened(env, &SIGNER).unwrap();
assert_eq!(
verify_causal(
"b",
Some(&CausedBy::Single(root)),
&store,
&proto,
&tid("t2")
),
VerificationResult::Unknown
);
}
#[test]
fn fan_in_type_check_resolves_through_opened_envelopes() {
let proto = fan_in_protocol();
let mut store = ThreadedMessageStore::new();
let t = tid("t1");
let (env_x, root_x) = opened_pred("x", "t1");
let (env_y, root_y) = opened_pred("y", "t1");
let z = CausedBy::Multiple(vec![root_x.clone(), root_y.clone()]);
store.append_opened(env_x, &SIGNER).unwrap();
assert_eq!(
verify_causal("z", Some(&z), &store, &proto, &t),
VerificationResult::Unknown,
"one member still missing"
);
store.append_opened(env_y, &SIGNER).unwrap();
assert_eq!(
verify_causal("z", Some(&z), &store, &proto, &t),
VerificationResult::Valid
);
}
}