1#![forbid(unsafe_code)]
15
16use crate::sexpr::{Atom, SExpr};
17use alloc::collections::{BTreeMap, BTreeSet};
18use alloc::format;
19use alloc::string::String;
20use alloc::vec::Vec;
21use core::fmt;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub enum RoleCardinality {
27 Singleton,
29 Indexed,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub struct RoleDecl {
38 pub name: String,
39 pub cardinality: RoleCardinality,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48pub struct RoleAnnotation {
49 pub from: String,
50 pub to: BTreeSet<String>,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct AgentKey(pub String);
61
62#[derive(Debug, Clone, PartialEq, Eq)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70pub struct Cast {
71 pub singleton: BTreeMap<String, AgentKey>,
72 pub indexed: BTreeMap<String, BTreeSet<AgentKey>>,
73 #[cfg_attr(feature = "serde", serde(default))]
78 pub dialect_pin: Option<String>,
79}
80
81impl Cast {
82 pub fn admits(&self, role: &str, key: &AgentKey) -> bool {
84 match self.singleton.get(role) {
85 Some(k) => k == key,
86 None => self.indexed.get(role).is_some_and(|ks| ks.contains(key)),
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95pub struct Endpoint {
96 pub role: String,
97 pub occupant: Option<AgentKey>,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Default)]
105#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
106pub enum CausalLocality {
107 #[default]
109 Reject,
110 Derive(EnvelopeRoutes),
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Default)]
127#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
128pub struct EnvelopeRoutes(pub BTreeMap<String, BTreeSet<String>>);
129
130impl EnvelopeRoutes {
131 pub fn routes_to(&self, performative: &str, role: &str) -> bool {
133 self.0.get(performative).is_some_and(|s| s.contains(role))
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Default)]
146#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
147pub struct OccupantEnvelopeRoutes(pub BTreeMap<String, BTreeSet<AgentKey>>);
148
149#[derive(Debug, Clone, PartialEq, Eq)]
152#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
153pub enum R6Violation {
154 MissingFromTo { performative: String },
156 UndeclaredRole { performative: String, role: String },
158 StrayAnnotation { performative: String },
160 ChooserIncoherent { members: Vec<String> },
162 NotCausallyLocal {
165 performative: String,
166 predecessor: String,
167 role: String,
168 },
169 UnreachableRole { role: String },
171 MalformedRoles { detail: String },
173 MalformedFromTo {
175 performative: String,
176 detail: String,
177 },
178 MalformedCast { detail: String },
180 UnknownRole { role: String },
182 ArityMismatch { role: String, keys: usize },
184 PerOccupantLocalityFailure {
186 performative: String,
187 occupant: String,
188 },
189 DialectPinMismatch { pinned: String, installed: String },
192}
193
194impl fmt::Display for R6Violation {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 match self {
197 R6Violation::MissingFromTo { performative } => write!(
198 f,
199 "R6 violation: performative '{performative}' lacks :from or :to (REQ-601)"
200 ),
201 R6Violation::UndeclaredRole { performative, role } => write!(
202 f,
203 "R6 violation: performative '{performative}' names undeclared role '{role}' (REQ-602)"
204 ),
205 R6Violation::StrayAnnotation { performative } => write!(
206 f,
207 "R6 violation: performative '{performative}' carries :from/:to but the dialect declares no :roles (REQ-602)"
208 ),
209 R6Violation::ChooserIncoherent { members } => write!(
210 f,
211 "R6 violation: choice {members:?} has no common sender role (REQ-603)"
212 ),
213 R6Violation::NotCausallyLocal {
214 performative,
215 predecessor,
216 role,
217 } => write!(
218 f,
219 "R6 violation: role '{role}' is an endpoint of '{performative}' but not of its predecessor '{predecessor}' (REQ-604)"
220 ),
221 R6Violation::UnreachableRole { role } => write!(
222 f,
223 "R6 violation: role '{role}' is not an endpoint of any performative reachable from begin (REQ-605)"
224 ),
225 R6Violation::MalformedRoles { detail } => {
226 write!(f, "R6 violation: malformed :roles — {detail} (CON-600)")
227 }
228 R6Violation::MalformedFromTo {
229 performative,
230 detail,
231 } => write!(
232 f,
233 "R6 violation: malformed :from/:to on '{performative}' — {detail} (CON-600)"
234 ),
235 R6Violation::MalformedCast { detail } => {
236 write!(f, "R6 violation: malformed cast — {detail} (CON-601)")
237 }
238 R6Violation::UnknownRole { role } => write!(
239 f,
240 "R6 violation: cast binds unknown role '{role}' (CON-601)"
241 ),
242 R6Violation::ArityMismatch { role, keys } => write!(
243 f,
244 "R6 violation: singleton role '{role}' bound to {keys} keys (CON-601)"
245 ),
246 R6Violation::PerOccupantLocalityFailure {
247 performative,
248 occupant,
249 } => write!(
250 f,
251 "R6 violation: '{performative}' fails per-occupant causal locality at occupant '{occupant}' (REQ-608)"
252 ),
253 R6Violation::DialectPinMismatch { pinned, installed } => write!(
254 f,
255 "R6 violation: root pins dialect '{pinned}' but the installed dialect hashes to '{installed}' (REQ-628)"
256 ),
257 }
258 }
259}
260
261pub fn parse_roles(roles_value: &SExpr) -> Result<Vec<RoleDecl>, R6Violation> {
268 let items = match roles_value {
269 SExpr::List(items) if !items.is_empty() => items,
270 SExpr::List(_) => {
271 return Err(R6Violation::MalformedRoles {
272 detail: String::from("empty :roles ()"),
273 })
274 }
275 _ => {
276 return Err(R6Violation::MalformedRoles {
277 detail: String::from(":roles value is not a list"),
278 })
279 }
280 };
281 let mut decls: Vec<RoleDecl> = Vec::with_capacity(items.len());
282 for item in items {
283 let decl = match item {
284 SExpr::Atom(Atom::Symbol(name)) => RoleDecl {
285 name: name.clone(),
286 cardinality: RoleCardinality::Singleton,
287 },
288 SExpr::List(marker) => match marker.as_slice() {
289 [SExpr::Atom(Atom::Symbol(star)), SExpr::Atom(Atom::Symbol(name))]
290 if star == "*" =>
291 {
292 RoleDecl {
293 name: name.clone(),
294 cardinality: RoleCardinality::Indexed,
295 }
296 }
297 _ => {
298 return Err(R6Violation::MalformedRoles {
299 detail: format!(
300 "role declaration must be a symbol or (* name), got {item}"
301 ),
302 })
303 }
304 },
305 _ => {
306 return Err(R6Violation::MalformedRoles {
307 detail: format!("role declaration must be a symbol or (* name), got {item}"),
308 })
309 }
310 };
311 if decls.iter().any(|d| d.name == decl.name) {
312 return Err(R6Violation::MalformedRoles {
313 detail: format!("duplicate role name '{}'", decl.name),
314 });
315 }
316 decls.push(decl);
317 }
318 Ok(decls)
319}
320
321pub fn parse_from(performative: &str, from_value: &SExpr) -> Result<String, R6Violation> {
324 match from_value {
325 SExpr::Atom(Atom::Symbol(role)) => Ok(role.clone()),
326 other => Err(R6Violation::MalformedFromTo {
327 performative: String::from(performative),
328 detail: format!(":from must be exactly one role symbol, got {other}"),
329 }),
330 }
331}
332
333pub fn parse_recipient_set(
337 performative: &str,
338 to_value: &SExpr,
339) -> Result<BTreeSet<String>, R6Violation> {
340 match to_value {
341 SExpr::Atom(Atom::Symbol(role)) => {
342 let mut set = BTreeSet::new();
343 set.insert(role.clone());
344 Ok(set)
345 }
346 SExpr::List(items) => {
347 let mut set = BTreeSet::new();
348 for item in items {
349 let SExpr::Atom(Atom::Symbol(role)) = item else {
350 return Err(R6Violation::MalformedFromTo {
351 performative: String::from(performative),
352 detail: format!(":to members must be role symbols, got {item}"),
353 });
354 };
355 if !set.insert(role.clone()) {
356 return Err(R6Violation::MalformedFromTo {
357 performative: String::from(performative),
358 detail: format!("duplicate :to member '{role}'"),
359 });
360 }
361 }
362 Ok(set)
363 }
364 other => Err(R6Violation::MalformedFromTo {
365 performative: String::from(performative),
366 detail: format!(":to must be a role symbol or a list, got {other}"),
367 }),
368 }
369}
370
371pub fn parse_cast(bindings: &SExpr, roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
379 let SExpr::List(items) = bindings else {
380 return Err(R6Violation::MalformedCast {
381 detail: String::from("bindings must be a list of (role key+) forms"),
382 });
383 };
384 let mut cast = Cast {
385 singleton: BTreeMap::new(),
386 indexed: BTreeMap::new(),
387 dialect_pin: None,
388 };
389 for item in items {
390 let SExpr::List(binding) = item else {
391 return Err(R6Violation::MalformedCast {
392 detail: format!("binding must be a (role key+) list, got {item}"),
393 });
394 };
395 let [SExpr::Atom(Atom::Symbol(role_name)), keys @ ..] = binding.as_slice() else {
396 return Err(R6Violation::MalformedCast {
397 detail: format!("binding must start with a role symbol, got {item}"),
398 });
399 };
400 let Some(decl) = roles.iter().find(|d| &d.name == role_name) else {
401 return Err(R6Violation::UnknownRole {
402 role: role_name.clone(),
403 });
404 };
405 if cast.singleton.contains_key(role_name) || cast.indexed.contains_key(role_name) {
406 return Err(R6Violation::MalformedCast {
407 detail: format!("duplicate binding for role '{role_name}'"),
408 });
409 }
410 let mut key_set: BTreeSet<AgentKey> = BTreeSet::new();
411 for key in keys {
412 let SExpr::Atom(Atom::Symbol(k)) = key else {
413 return Err(R6Violation::MalformedCast {
414 detail: format!("key must be a symbol, got {key}"),
415 });
416 };
417 if !key_set.insert(AgentKey(k.clone())) {
418 return Err(R6Violation::MalformedCast {
419 detail: format!("duplicate key '{k}' for role '{role_name}'"),
420 });
421 }
422 }
423 match decl.cardinality {
424 RoleCardinality::Singleton => {
425 if key_set.len() != 1 {
426 return Err(R6Violation::ArityMismatch {
427 role: role_name.clone(),
428 keys: key_set.len(),
429 });
430 }
431 let key = key_set.into_iter().next().expect("len == 1");
432 cast.singleton.insert(role_name.clone(), key);
433 }
434 RoleCardinality::Indexed => {
435 if key_set.is_empty() {
436 return Err(R6Violation::MalformedCast {
437 detail: format!("indexed role '{role_name}' bound to no keys"),
438 });
439 }
440 cast.indexed.insert(role_name.clone(), key_set);
441 }
442 }
443 }
444 for decl in roles {
445 let bound =
446 cast.singleton.contains_key(&decl.name) || cast.indexed.contains_key(&decl.name);
447 if !bound {
448 return Err(R6Violation::MalformedCast {
449 detail: format!("declared role '{}' is not bound by the cast", decl.name),
450 });
451 }
452 }
453 Ok(cast)
454}
455
456const PIN_HEX_LEN: usize = 64;
458
459pub fn parse_dialect_pin(value: &SExpr) -> Result<String, R6Violation> {
467 let pin = match value {
468 SExpr::Atom(Atom::Str(pin) | Atom::Symbol(pin)) => pin,
469 _ => {
470 return Err(R6Violation::MalformedCast {
471 detail: format!(
472 ":dialect value must be a f1220<hex64> string or typed symbol, got {value}"
473 ),
474 })
475 }
476 };
477 let Some(hex) = pin.strip_prefix("f1220") else {
478 return Err(R6Violation::MalformedCast {
479 detail: format!(":dialect value must start with 'f1220', got '{pin}'"),
480 });
481 };
482 if hex.len() != PIN_HEX_LEN || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
483 return Err(R6Violation::MalformedCast {
484 detail: format!(
485 ":dialect digest must be exactly {PIN_HEX_LEN} lowercase hex characters, got '{hex}'"
486 ),
487 });
488 }
489 Ok(pin.clone())
490}
491
492pub fn parse_wrapper_cast(params: &[SExpr], roles: &[RoleDecl]) -> Result<Cast, R6Violation> {
498 let (bindings, pin) = match params {
499 [bindings] => (bindings, None),
500 [bindings, SExpr::Atom(Atom::Keyword(k)), value] if k == "dialect" => {
501 (bindings, Some(parse_dialect_pin(value)?))
502 }
503 _ => {
504 return Err(R6Violation::MalformedCast {
505 detail: String::from(
506 "with-roles wrapper must carry exactly one bindings list, \
507 optionally followed by :dialect f1220<hex64> (CON-601, REQ-628)",
508 ),
509 })
510 }
511 };
512 let mut cast = parse_cast(bindings, roles)?;
513 cast.dialect_pin = pin;
514 Ok(cast)
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520 use alloc::string::ToString;
521 use alloc::vec;
522
523 fn sx(s: &str) -> SExpr {
524 s.parse().expect("test fixture parses")
525 }
526
527 #[test]
532 fn violation_display_carries_locating_names() {
533 use alloc::string::ToString as _;
534 let v = R6Violation::NotCausallyLocal {
535 performative: "dispatch".to_string(),
536 predecessor: "accept".to_string(),
537 role: "warehouse".to_string(),
538 };
539 let s = alloc::format!("{v}");
540 assert!(s.contains("dispatch") && s.contains("accept") && s.contains("warehouse"));
541 assert!(s.contains("REQ-604"));
542
543 let a = R6Violation::ArityMismatch {
544 role: "auctioneer".to_string(),
545 keys: 2,
546 };
547 let s = alloc::format!("{a}");
548 assert!(s.contains("auctioneer") && s.contains('2') && s.contains("CON-601"));
549 }
550
551 fn auction_roles() -> Vec<RoleDecl> {
552 vec![
553 RoleDecl {
554 name: "auctioneer".to_string(),
555 cardinality: RoleCardinality::Singleton,
556 },
557 RoleDecl {
558 name: "bidder".to_string(),
559 cardinality: RoleCardinality::Indexed,
560 },
561 ]
562 }
563
564 #[test]
567 fn roles_positive_singleton_and_indexed() {
568 let decls = parse_roles(&sx("(auctioneer (* bidder))")).unwrap();
569 assert_eq!(decls, auction_roles());
570 }
571
572 #[test]
573 fn roles_negative_empty_list() {
574 assert!(matches!(
575 parse_roles(&sx("()")),
576 Err(R6Violation::MalformedRoles { .. })
577 ));
578 }
579
580 #[test]
581 fn roles_negative_not_a_list() {
582 assert!(matches!(
583 parse_roles(&sx("auctioneer")),
584 Err(R6Violation::MalformedRoles { .. })
585 ));
586 }
587
588 #[test]
589 fn roles_negative_postfix_marker() {
590 assert!(matches!(
592 parse_roles(&sx("((bidder *))")),
593 Err(R6Violation::MalformedRoles { .. })
594 ));
595 }
596
597 #[test]
598 fn roles_negative_marker_arity() {
599 assert!(matches!(
600 parse_roles(&sx("((*))")),
601 Err(R6Violation::MalformedRoles { .. })
602 ));
603 assert!(matches!(
604 parse_roles(&sx("((* a b))")),
605 Err(R6Violation::MalformedRoles { .. })
606 ));
607 }
608
609 #[test]
610 fn roles_negative_non_symbol_entry() {
611 assert!(matches!(
612 parse_roles(&sx("(auctioneer 42)")),
613 Err(R6Violation::MalformedRoles { .. })
614 ));
615 }
616
617 #[test]
618 fn roles_negative_duplicate_names() {
619 assert!(matches!(
620 parse_roles(&sx("(a (* a))")),
621 Err(R6Violation::MalformedRoles { .. })
622 ));
623 }
624
625 #[test]
628 fn from_positive_symbol() {
629 assert_eq!(parse_from("login", &sx("server")).unwrap(), "server");
630 }
631
632 #[test]
633 fn from_negative_list() {
634 assert!(matches!(
635 parse_from("login", &sx("(server client)")),
636 Err(R6Violation::MalformedFromTo { .. })
637 ));
638 }
639
640 #[test]
641 fn to_positive_bare_symbol_is_singleton_set() {
642 let set = parse_recipient_set("login", &sx("client")).unwrap();
643 assert_eq!(set.len(), 1);
644 assert!(set.contains("client"));
645 }
646
647 #[test]
648 fn to_positive_multicast() {
649 let set = parse_recipient_set("login", &sx("(client authoriser)")).unwrap();
650 assert_eq!(set.len(), 2);
651 assert!(set.contains("client") && set.contains("authoriser"));
652 }
653
654 #[test]
655 fn to_positive_empty_terminal() {
656 let set = parse_recipient_set("declare-winner", &sx("()")).unwrap();
657 assert!(set.is_empty());
658 }
659
660 #[test]
661 fn to_negative_non_symbol_member() {
662 assert!(matches!(
663 parse_recipient_set("login", &sx("(client 7)")),
664 Err(R6Violation::MalformedFromTo { .. })
665 ));
666 }
667
668 #[test]
669 fn to_negative_duplicate_member() {
670 assert!(matches!(
671 parse_recipient_set("login", &sx("(client client)")),
672 Err(R6Violation::MalformedFromTo { .. })
673 ));
674 }
675
676 #[test]
679 fn cast_positive_auction() {
680 let cast = parse_cast(
681 &sx("((auctioneer @auc) (bidder @b1 @b2 @b3))"),
682 &auction_roles(),
683 )
684 .unwrap();
685 assert_eq!(
686 cast.singleton.get("auctioneer"),
687 Some(&AgentKey("@auc".to_string()))
688 );
689 let members = cast.indexed.get("bidder").unwrap();
690 assert_eq!(members.len(), 3);
691 assert!(cast.admits("bidder", &AgentKey("@b2".to_string())));
692 assert!(!cast.admits("bidder", &AgentKey("@b4".to_string())));
693 assert!(cast.admits("auctioneer", &AgentKey("@auc".to_string())));
694 }
695
696 #[test]
697 fn cast_negative_singleton_two_keys() {
698 assert!(matches!(
699 parse_cast(&sx("((auctioneer @a @b) (bidder @b1))"), &auction_roles()),
700 Err(R6Violation::ArityMismatch { keys: 2, .. })
701 ));
702 }
703
704 #[test]
705 fn cast_negative_unknown_role() {
706 assert!(matches!(
707 parse_cast(
708 &sx("((auctioneer @auc) (bidder @b1) (ghost @g))"),
709 &auction_roles()
710 ),
711 Err(R6Violation::UnknownRole { .. })
712 ));
713 }
714
715 #[test]
716 fn cast_negative_missing_binding() {
717 assert!(matches!(
718 parse_cast(&sx("((auctioneer @auc))"), &auction_roles()),
719 Err(R6Violation::MalformedCast { .. })
720 ));
721 }
722
723 #[test]
724 fn cast_negative_duplicate_binding() {
725 assert!(matches!(
726 parse_cast(
727 &sx("((auctioneer @auc) (auctioneer @b) (bidder @b1))"),
728 &auction_roles()
729 ),
730 Err(R6Violation::MalformedCast { .. })
731 ));
732 }
733
734 #[test]
735 fn cast_negative_indexed_no_keys() {
736 assert!(matches!(
737 parse_cast(&sx("((auctioneer @auc) (bidder))"), &auction_roles()),
738 Err(R6Violation::MalformedCast { .. })
739 ));
740 }
741
742 #[test]
743 fn cast_negative_non_list_binding() {
744 assert!(matches!(
745 parse_cast(&sx("(auctioneer @auc)"), &auction_roles()),
746 Err(R6Violation::MalformedCast { .. })
747 ));
748 }
749
750 fn hex64(c: char) -> String {
753 core::iter::repeat(c).take(64).collect()
754 }
755
756 #[test]
757 fn wrapper_cast_without_pin_has_none() {
758 let cast = parse_wrapper_cast(&[sx("((auctioneer @auc) (bidder @b1))")], &auction_roles())
759 .unwrap();
760 assert_eq!(cast.dialect_pin, None);
761 }
762
763 #[test]
764 fn wrapper_cast_with_wellformed_pin_carries_it() {
765 let pin = alloc::format!("f1220{}", hex64('a'));
766 let cast = parse_wrapper_cast(
767 &[
768 sx("((auctioneer @auc) (bidder @b1))"),
769 sx(":dialect"),
770 sx(&pin),
771 ],
772 &auction_roles(),
773 )
774 .unwrap();
775 assert_eq!(cast.dialect_pin.as_deref(), Some(pin.as_str()));
776 }
777
778 #[test]
779 fn pin_negative_bad_prefix() {
780 assert!(matches!(
781 parse_dialect_pin(&sx(&alloc::format!("md5:{}", hex64('a')))),
782 Err(R6Violation::MalformedCast { .. })
783 ));
784 }
785
786 #[test]
787 fn pin_negative_wrong_length() {
788 assert!(matches!(
789 parse_dialect_pin(&sx("f1220abc")),
790 Err(R6Violation::MalformedCast { .. })
791 ));
792 assert!(matches!(
793 parse_dialect_pin(&sx(&alloc::format!("f1220{}a", hex64('a')))),
794 Err(R6Violation::MalformedCast { .. })
795 ));
796 }
797
798 #[test]
799 fn pin_negative_non_hex_digits() {
800 assert!(matches!(
803 parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('g')))),
804 Err(R6Violation::MalformedCast { .. })
805 ));
806 assert!(matches!(
807 parse_dialect_pin(&sx(&alloc::format!("f1220{}", hex64('A')))),
808 Err(R6Violation::MalformedCast { .. })
809 ));
810 }
811
812 #[test]
813 fn pin_negative_non_text_value() {
814 assert!(matches!(
815 parse_dialect_pin(&sx("(sha256 x)")),
816 Err(R6Violation::MalformedCast { .. })
817 ));
818 }
819
820 #[test]
821 fn wrapper_cast_negative_extra_fields() {
822 let pin = alloc::format!("f1220{}", hex64('a'));
823 assert!(matches!(
825 parse_wrapper_cast(
826 &[
827 sx("((auctioneer @auc) (bidder @b1))"),
828 sx(":dialect"),
829 sx(&pin),
830 sx("junk"),
831 ],
832 &auction_roles(),
833 ),
834 Err(R6Violation::MalformedCast { .. })
835 ));
836 assert!(matches!(
838 parse_wrapper_cast(
839 &[
840 sx("((auctioneer @auc) (bidder @b1))"),
841 sx(":lang"),
842 sx(&pin),
843 ],
844 &auction_roles(),
845 ),
846 Err(R6Violation::MalformedCast { .. })
847 ));
848 }
849}