1#![forbid(unsafe_code)]
7
8use crate::protocol::CausalProtocol;
9use crate::r1::{r1_violations, verify_r1_dialect};
10use crate::r2::verify_r2;
11use crate::r3::{r3_violations, verify_r3};
12use crate::r4::{check_r4, R4Result, Signer};
13use crate::r5::{r5_violations_with_ancestors, verify_r5_with_ancestors};
14use crate::r6::{derive_envelope_routes, r6_violations};
15use crate::role::{CausalLocality, R6Violation as R6ViolationDetail, RoleAnnotation, RoleDecl};
16use crate::sexpr::{Atom, SExpr};
17use crate::shape::ShapeConstraint;
18use alloc::string::String;
19use alloc::vec;
20use alloc::vec::Vec;
21use core::fmt;
22
23#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub struct ResourceBounds {
27 pub max_depth: u32,
28 pub max_expansion_size: u32,
29}
30
31impl ResourceBounds {
32 pub fn is_valid(&self) -> bool {
34 self.max_depth > 0
35 && self.max_depth <= 64
36 && self.max_expansion_size > 0
37 && self.max_expansion_size <= 8192
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum DialectInstallError {
44 ResourceLimit {
45 dialect_name: String,
46 detail: String,
47 },
48 R1Violation {
50 dialect_name: String,
51 recursive: Vec<String>,
52 },
53 R2Violation { dialect_name: String },
55 R2ProtocolBudgetExceeded {
60 dialect_name: String,
61 expanded_steps: u32,
63 budget: u32,
65 },
66 R3Violation {
68 dialect_name: String,
69 redefined: Vec<String>,
70 },
71 R4Violation { dialect_name: String },
73 R7Violation {
76 dialect_name: String,
77 violations: Vec<crate::r7::R7Violation>,
78 },
79 R5Violation {
81 dialect_name: String,
82 shape_errors: Vec<String>,
83 },
84 R6Violation {
87 dialect_name: String,
88 violations: Vec<R6ViolationDetail>,
89 },
90}
91
92impl fmt::Display for DialectInstallError {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 match self {
95 DialectInstallError::ResourceLimit {
96 dialect_name,
97 detail,
98 } => write!(f, "resource-limit: dialect {dialect_name}: {detail}"),
99 DialectInstallError::R1Violation {
100 dialect_name,
101 recursive,
102 } => {
103 write!(
104 f,
105 "R1 violation: dialect '{}' has recursive performative(s): {}",
106 dialect_name,
107 recursive.join(", ")
108 )
109 }
110 DialectInstallError::R2Violation { dialect_name } => {
111 write!(
112 f,
113 "R2 violation: dialect '{}' has invalid resource bounds",
114 dialect_name,
115 )
116 }
117 DialectInstallError::R2ProtocolBudgetExceeded {
118 dialect_name,
119 expanded_steps,
120 budget,
121 } => {
122 write!(
123 f,
124 "R2 violation: dialect '{}' protocol expands to {} steps, \
125 exceeding the declared expansion budget {}",
126 dialect_name, expanded_steps, budget,
127 )
128 }
129 DialectInstallError::R3Violation {
130 dialect_name,
131 redefined,
132 } => {
133 write!(
134 f,
135 "R3 violation: dialect '{}' redefines core performative(s): {}",
136 dialect_name,
137 redefined.join(", ")
138 )
139 }
140 DialectInstallError::R4Violation { dialect_name } => {
141 write!(
142 f,
143 "R4 violation: dialect '{}' has an invalid signature",
144 dialect_name,
145 )
146 }
147 DialectInstallError::R5Violation {
148 dialect_name,
149 shape_errors,
150 } => {
151 write!(
152 f,
153 "R5 violation: dialect '{}' has malformed shape(s): {}",
154 dialect_name,
155 shape_errors.join("; ")
156 )
157 }
158 DialectInstallError::R6Violation {
159 dialect_name,
160 violations,
161 } => {
162 write!(f, "R6 violation: dialect '{dialect_name}':")?;
163 for v in violations {
164 write!(f, " {v};")?;
165 }
166 Ok(())
167 }
168 DialectInstallError::R7Violation {
169 dialect_name,
170 violations,
171 } => {
172 write!(f, "R7 violation: dialect '{dialect_name}':")?;
173 for v in violations {
174 write!(f, " {v};")?;
175 }
176 Ok(())
177 }
178 }
179 }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
184#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
185pub struct PerformativeDef {
186 pub name: String,
187 pub params: Vec<SExpr>,
188 pub template: SExpr,
189 #[cfg_attr(feature = "serde", serde(default))]
191 pub role: Option<RoleAnnotation>,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
198#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
199pub struct Dialect {
200 #[cfg_attr(feature = "serde", serde(default))]
201 pub types: alloc::collections::BTreeMap<String, SExpr>,
202 pub name: String,
203 pub extends: Vec<String>,
205 pub author: Option<String>,
206 pub performatives: Vec<PerformativeDef>,
207 pub resources: ResourceBounds,
208 pub examples: Vec<SExpr>,
209 pub signature: Option<Vec<u8>>,
210 pub hash: Option<String>,
219 pub protocol: Option<String>,
220 pub causal_protocol: Option<CausalProtocol>,
222 pub shapes: Vec<ShapeConstraint>,
224 #[cfg_attr(feature = "serde", serde(default))]
226 pub roles: Vec<RoleDecl>,
227 #[cfg_attr(feature = "serde", serde(default))]
232 pub causal_locality: CausalLocality,
233 #[cfg_attr(feature = "serde", serde(default))]
235 pub state: Option<crate::state::StateClause>,
236 #[cfg_attr(feature = "serde", serde(default))]
238 pub state_bounds: Option<crate::state::StateBounds>,
239}
240
241impl Dialect {
242 pub fn defines_performative(&self, name: &str) -> bool {
244 self.performatives.iter().any(|p| p.name == name)
245 }
246
247 pub fn find_performative(&self, name: &str) -> Option<&PerformativeDef> {
249 self.performatives.iter().find(|p| p.name == name)
250 }
251
252 pub fn performative_names(&self) -> Vec<&str> {
254 self.performatives.iter().map(|p| p.name.as_str()).collect()
255 }
256}
257
258fn effect_template(action: &str) -> SExpr {
260 SExpr::List(vec![
261 SExpr::Atom(Atom::Symbol(String::from("effect"))),
262 SExpr::Atom(Atom::Symbol(String::from(action))),
263 ])
264}
265
266const CORE_EFFECT_ACTIONS: [(&str, &str); 8] = [
268 ("tell", "send-message"),
269 ("ask", "send-query"),
270 ("reply", "send-reply"),
271 ("error", "signal-error"),
272 ("ok", "acknowledge"),
273 ("cancel", "cancel-conversation"),
274 ("hello", "announce-presence"),
275 ("bye", "announce-departure"),
276];
277
278pub fn base_dialect() -> Dialect {
283 Dialect {
284 types: Default::default(),
285 state: None,
286 state_bounds: None,
287 causal_locality: CausalLocality::Reject,
288 roles: Vec::new(),
289 name: String::from("cbcl-base"),
290 extends: Vec::new(),
291 author: Some(String::from("@cbcl-system")),
292 performatives: CORE_EFFECT_ACTIONS
293 .iter()
294 .map(|&(name, action)| PerformativeDef {
295 role: None,
296 name: String::from(name),
297 params: Vec::new(),
298 template: effect_template(action),
299 })
300 .collect(),
301 resources: ResourceBounds {
302 max_depth: 8,
303 max_expansion_size: 512,
304 },
305 examples: Vec::new(),
306 signature: None,
307 hash: None,
308 protocol: None,
309 causal_protocol: None,
310 shapes: Vec::new(),
311 }
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
326#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
327pub struct DialectRegistry {
328 dialects: Vec<Dialect>,
329}
330
331impl DialectRegistry {
332 pub fn new() -> Self {
334 Self {
335 dialects: vec![base_dialect()],
336 }
337 }
338
339 pub fn install(&mut self, mut d: Dialect) -> Result<(), DialectInstallError> {
349 crate::contracts::install(&mut d).map_err(|error| {
350 if error.starts_with("resource-limit:") {
351 DialectInstallError::ResourceLimit {
352 dialect_name: d.name.clone(),
353 detail: error,
354 }
355 } else {
356 DialectInstallError::R5Violation {
357 dialect_name: d.name.clone(),
358 shape_errors: alloc::vec![error],
359 }
360 }
361 })?;
362 if let Some(state) = &mut d.state {
363 state.resolve_lattices();
364 }
365 if !verify_r1_dialect(&d) {
366 return Err(DialectInstallError::R1Violation {
367 recursive: r1_violations(&d),
368 dialect_name: d.name,
369 });
370 }
371 if !verify_r2(&d) {
372 return Err(DialectInstallError::R2Violation {
373 dialect_name: d.name,
374 });
375 }
376 Self::check_protocol_expansion_budget(&d)?;
377 if !verify_r3(&d) {
378 return Err(DialectInstallError::R3Violation {
379 redefined: r3_violations(&d),
380 dialect_name: d.name,
381 });
382 }
383 let ancestors = self.resolve_ancestors(&d);
384 if !verify_r5_with_ancestors(&d, &ancestors) {
385 return Err(DialectInstallError::R5Violation {
386 shape_errors: r5_violations_with_ancestors(&d, &ancestors),
387 dialect_name: d.name,
388 });
389 }
390 Self::apply_r6(&mut d)?;
395 crate::context::resolve(&mut d);
396 let r7 = crate::r7::r7_violations(&d);
399 if !r7.is_empty() {
400 return Err(DialectInstallError::R7Violation {
401 dialect_name: d.name,
402 violations: r7,
403 });
404 }
405 Self::ensure_hash(&mut d);
406 #[cfg(feature = "tracing")]
407 tracing::event!(
408 tracing::Level::INFO,
409 dialect = %d.name,
410 "dialect_install_count"
411 );
412 crate::canonical::canonicalise_dialect(&mut d);
413 self.dialects.push(d);
414 Ok(())
415 }
416
417 fn apply_r6(d: &mut Dialect) -> Result<(), DialectInstallError> {
427 let r6 = r6_violations(d);
428 let deriving = matches!(d.causal_locality, CausalLocality::Derive(_));
429 let violations: Vec<R6ViolationDetail> = if deriving {
430 r6.into_iter()
431 .filter(|v| !matches!(v, R6ViolationDetail::NotCausallyLocal { .. }))
432 .collect()
433 } else {
434 r6
435 };
436 if !violations.is_empty() {
437 return Err(DialectInstallError::R6Violation {
438 violations,
439 dialect_name: d.name.clone(),
440 });
441 }
442 if deriving {
443 d.causal_locality = CausalLocality::Derive(derive_envelope_routes(d));
448 }
449 Ok(())
450 }
451
452 fn ensure_hash(d: &mut Dialect) {
466 if d.hash.is_none() {
467 d.hash = Some(crate::canonical::dialect_hash(d));
468 }
469 }
470
471 fn check_protocol_expansion_budget(d: &Dialect) -> Result<(), DialectInstallError> {
481 if let Some(cp) = &d.causal_protocol {
482 let expanded_steps = cp.expansion_size();
483 if expanded_steps >= d.resources.max_expansion_size {
484 return Err(DialectInstallError::R2ProtocolBudgetExceeded {
485 dialect_name: d.name.clone(),
486 expanded_steps,
487 budget: d.resources.max_expansion_size,
488 });
489 }
490 }
491 Ok(())
492 }
493
494 pub fn resolve_ancestors<'a>(&'a self, d: &Dialect) -> Vec<&'a Dialect> {
506 d.extends
507 .iter()
508 .filter_map(|name| {
509 let resolved = if name == "cbcl" {
510 "cbcl-base"
511 } else {
512 name.as_str()
513 };
514 self.find_by_name(resolved)
515 })
516 .collect()
517 }
518
519 pub fn install_with_signer(
529 &mut self,
530 mut d: Dialect,
531 signer: &dyn Signer,
532 ) -> Result<R4Result, DialectInstallError> {
533 crate::contracts::install(&mut d).map_err(|error| {
534 if error.starts_with("resource-limit:") {
535 DialectInstallError::ResourceLimit {
536 dialect_name: d.name.clone(),
537 detail: error,
538 }
539 } else {
540 DialectInstallError::R5Violation {
541 dialect_name: d.name.clone(),
542 shape_errors: alloc::vec![error],
543 }
544 }
545 })?;
546 if !verify_r1_dialect(&d) {
548 return Err(DialectInstallError::R1Violation {
549 recursive: r1_violations(&d),
550 dialect_name: d.name,
551 });
552 }
553 if !verify_r2(&d) {
554 return Err(DialectInstallError::R2Violation {
555 dialect_name: d.name,
556 });
557 }
558 Self::check_protocol_expansion_budget(&d)?;
559 if !verify_r3(&d) {
560 return Err(DialectInstallError::R3Violation {
561 redefined: r3_violations(&d),
562 dialect_name: d.name,
563 });
564 }
565 let ancestors = self.resolve_ancestors(&d);
566 if !verify_r5_with_ancestors(&d, &ancestors) {
567 return Err(DialectInstallError::R5Violation {
568 shape_errors: r5_violations_with_ancestors(&d, &ancestors),
569 dialect_name: d.name,
570 });
571 }
572 Self::apply_r6(&mut d)?;
577 let r4 = check_r4(&d, signer);
582 if r4 == R4Result::Invalid {
583 return Err(DialectInstallError::R4Violation {
584 dialect_name: d.name,
585 });
586 }
587 Self::ensure_hash(&mut d);
591 #[cfg(feature = "tracing")]
592 tracing::event!(
593 tracing::Level::INFO,
594 dialect = %d.name,
595 r4_result = ?r4,
596 "dialect_install_count"
597 );
598 crate::canonical::canonicalise_dialect(&mut d);
599 self.dialects.push(d);
600 Ok(r4)
601 }
602
603 pub fn len(&self) -> usize {
605 self.dialects.len()
606 }
607
608 pub fn is_empty(&self) -> bool {
610 false
611 }
612
613 pub fn is_well_formed(&self) -> bool {
615 !self.dialects.is_empty() && self.dialects[0] == base_dialect()
616 }
617
618 pub fn get(&self, index: usize) -> Option<&Dialect> {
620 self.dialects.get(index)
621 }
622
623 pub fn find_by_name(&self, name: &str) -> Option<&Dialect> {
625 self.dialects.iter().find(|d| d.name == name)
626 }
627
628 pub fn base_definer_of(&self, name: &str) -> Option<&Dialect> {
640 self.dialects
641 .first()
642 .filter(|d| d.defines_performative(name))
643 }
644
645 pub fn dialects_defining<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Dialect> {
652 self.dialects
653 .iter()
654 .filter(move |d| d.defines_performative(name))
655 }
656
657 pub fn iter(&self) -> core::slice::Iter<'_, Dialect> {
659 self.dialects.iter()
660 }
661
662 pub fn as_slice(&self) -> &[Dialect] {
664 &self.dialects
665 }
666}
667
668impl Default for DialectRegistry {
669 fn default() -> Self {
670 Self::new()
671 }
672}
673
674impl<'a> IntoIterator for &'a DialectRegistry {
675 type Item = &'a Dialect;
676 type IntoIter = core::slice::Iter<'a, Dialect>;
677
678 fn into_iter(self) -> Self::IntoIter {
679 self.iter()
680 }
681}
682
683#[cfg(test)]
684mod tests {
685 use super::*;
686
687 #[test]
688 fn base_dialect_has_8_performatives() {
689 let d = base_dialect();
690 assert_eq!(d.performatives.len(), 8);
691 assert_eq!(d.name, "cbcl-base");
692 }
693
694 #[test]
695 fn base_dialect_templates_are_effect_forms() {
696 let d = base_dialect();
697 let tell = d.find_performative("tell").unwrap();
698 match &tell.template {
700 SExpr::List(items) => {
701 assert_eq!(items.len(), 2);
702 assert!(items[0].is_symbol("effect"));
703 assert!(items[1].is_symbol("send-message"));
704 }
705 _ => panic!("expected list template"),
706 }
707 }
708
709 #[test]
710 fn base_dialect_resource_bounds_valid() {
711 let d = base_dialect();
712 assert!(d.resources.is_valid());
713 }
714
715 #[test]
716 fn base_dialect_extends_is_empty() {
717 let d = base_dialect();
718 assert!(d.extends.is_empty());
719 }
720
721 #[test]
722 fn defines_and_find_performative() {
723 let d = base_dialect();
724 assert!(d.defines_performative("tell"));
725 assert!(!d.defines_performative("nonexistent"));
726 assert!(d.find_performative("ask").is_some());
727 }
728
729 #[test]
730 fn performative_names() {
731 let d = base_dialect();
732 let names = d.performative_names();
733 assert_eq!(names.len(), 8);
734 assert!(names.contains(&"tell"));
735 assert!(names.contains(&"bye"));
736 }
737
738 #[test]
739 fn resource_bounds_validation() {
740 let valid = ResourceBounds {
741 max_depth: 8,
742 max_expansion_size: 512,
743 };
744 assert!(valid.is_valid());
745
746 let invalid = ResourceBounds {
747 max_depth: 0,
748 max_expansion_size: 512,
749 };
750 assert!(!invalid.is_valid());
751
752 let too_large = ResourceBounds {
753 max_depth: 65,
754 max_expansion_size: 512,
755 };
756 assert!(!too_large.is_valid());
757 }
758
759 #[test]
762 fn registry_new_has_base_dialect() {
763 let reg = DialectRegistry::new();
764 assert_eq!(reg.len(), 1);
765 assert!(reg.is_well_formed());
766 assert_eq!(reg.get(0).unwrap().name, "cbcl-base");
767 }
768
769 #[test]
770 fn registry_install_appends() {
771 let mut reg = DialectRegistry::new();
772 let planning = Dialect {
773 types: Default::default(),
774 roles: Vec::new(),
775 state: None,
776 state_bounds: None,
777 causal_locality: Default::default(),
778 name: String::from("cbcl-planning"),
779 extends: vec![String::from("cbcl")],
780 author: Some(String::from("@planning-authority")),
781 performatives: vec![PerformativeDef {
782 role: None,
783 name: String::from("propose-step"),
784 params: vec![],
785 template: effect_template("propose"),
786 }],
787 resources: ResourceBounds {
788 max_depth: 16,
789 max_expansion_size: 1024,
790 },
791 examples: vec![],
792 signature: None,
793 hash: None,
794 protocol: Some(String::from("ed25519")),
795 causal_protocol: None,
796 shapes: Vec::new(),
797 };
798 reg.install(planning).unwrap();
799 assert_eq!(reg.len(), 2);
800 assert!(reg.is_well_formed());
801 assert_eq!(reg.get(1).unwrap().name, "cbcl-planning");
802 }
803
804 fn greeter(name: &str) -> Dialect {
806 Dialect {
807 types: Default::default(),
808 roles: Vec::new(),
809 state: None,
810 state_bounds: None,
811 causal_locality: Default::default(),
812 name: String::from(name),
813 extends: vec![String::from("cbcl")],
814 author: None,
815 performatives: vec![PerformativeDef {
816 role: None,
817 name: String::from("greet"),
818 params: vec![],
819 template: effect_template("greet-action"),
820 }],
821 resources: ResourceBounds {
822 max_depth: 8,
823 max_expansion_size: 512,
824 },
825 examples: vec![],
826 signature: None,
827 hash: None,
828 protocol: None,
829 causal_protocol: None,
830 shapes: Vec::new(),
831 }
832 }
833
834 #[test]
835 fn base_definer_of_finds_core_performatives() {
836 let reg = DialectRegistry::new();
837 assert_eq!(reg.base_definer_of("tell").unwrap().name, "cbcl-base");
838 }
839
840 #[test]
843 fn base_definer_of_ignores_installed_dialects() {
844 let mut reg = DialectRegistry::new();
845 reg.install(greeter("first")).unwrap();
846 assert!(reg.base_definer_of("greet").is_none());
847 }
848
849 #[test]
853 fn dialects_defining_reports_every_definer_in_install_order() {
854 let mut reg = DialectRegistry::new();
855 reg.install(greeter("first")).unwrap();
856 reg.install(greeter("second")).unwrap();
857 let names: Vec<&str> = reg
858 .dialects_defining("greet")
859 .map(|d| d.name.as_str())
860 .collect();
861 assert_eq!(names, vec!["first", "second"]);
862 }
863
864 #[test]
865 fn registry_install_rejects_r3_violation() {
866 let mut reg = DialectRegistry::new();
867 let bad = Dialect {
868 types: Default::default(),
869 roles: Vec::new(),
870 state: None,
871 state_bounds: None,
872 causal_locality: Default::default(),
873 name: String::from("bad-dialect"),
874 extends: vec![String::from("cbcl")],
875 author: None,
876 performatives: vec![PerformativeDef {
877 role: None,
878 name: String::from("tell"),
879 params: vec![],
880 template: effect_template("custom-tell"),
881 }],
882 resources: ResourceBounds {
883 max_depth: 8,
884 max_expansion_size: 512,
885 },
886 examples: vec![],
887 signature: None,
888 hash: None,
889 protocol: None,
890 causal_protocol: None,
891 shapes: Vec::new(),
892 };
893 let err = reg.install(bad).unwrap_err();
894 match err {
895 DialectInstallError::R3Violation {
896 dialect_name,
897 redefined,
898 } => {
899 assert_eq!(dialect_name, "bad-dialect");
900 assert_eq!(redefined, vec!["tell"]);
901 }
902 other => panic!("expected R3Violation, got {:?}", other),
903 }
904 assert_eq!(reg.len(), 1);
906 }
907
908 #[test]
909 fn registry_install_rejects_r2_violation() {
910 let mut reg = DialectRegistry::new();
911 let bad = Dialect {
912 types: Default::default(),
913 roles: Vec::new(),
914 state: None,
915 state_bounds: None,
916 causal_locality: Default::default(),
917 name: String::from("bad-bounds"),
918 extends: vec![String::from("cbcl")],
919 author: None,
920 performatives: vec![],
921 resources: ResourceBounds {
922 max_depth: 100, max_expansion_size: 512,
924 },
925 examples: vec![],
926 signature: None,
927 hash: None,
928 protocol: None,
929 causal_protocol: None,
930 shapes: Vec::new(),
931 };
932 let err = reg.install(bad).unwrap_err();
933 match err {
934 DialectInstallError::R2Violation { dialect_name } => {
935 assert_eq!(dialect_name, "bad-bounds");
936 }
937 _ => panic!("expected R2Violation"),
938 }
939 assert_eq!(reg.len(), 1);
941 }
942
943 #[test]
944 fn registry_install_rejects_zero_bounds() {
945 let mut reg = DialectRegistry::new();
946 let bad = Dialect {
947 types: Default::default(),
948 roles: Vec::new(),
949 state: None,
950 state_bounds: None,
951 causal_locality: Default::default(),
952 name: String::from("zero-depth"),
953 extends: vec![],
954 author: None,
955 performatives: vec![],
956 resources: ResourceBounds {
957 max_depth: 0,
958 max_expansion_size: 512,
959 },
960 examples: vec![],
961 signature: None,
962 hash: None,
963 protocol: None,
964 causal_protocol: None,
965 shapes: Vec::new(),
966 };
967 assert!(matches!(
968 reg.install(bad),
969 Err(DialectInstallError::R2Violation { .. })
970 ));
971 }
972
973 #[test]
974 fn registry_find_by_name() {
975 let reg = DialectRegistry::new();
976 assert!(reg.find_by_name("cbcl-base").is_some());
977 assert!(reg.find_by_name("nonexistent").is_none());
978 }
979
980 #[test]
981 fn registry_is_never_empty() {
982 let reg = DialectRegistry::new();
983 assert!(!reg.is_empty());
984 }
985
986 #[test]
987 fn registry_multi_dialect_install() {
988 let mut reg = DialectRegistry::new();
990 for name in &[
991 "cbcl-planning",
992 "cbcl-crosschain-transfer",
993 "cbcl-artifacts",
994 ] {
995 reg.install(Dialect {
996 types: Default::default(),
997 roles: Vec::new(),
998 state: None,
999 state_bounds: None,
1000 causal_locality: Default::default(),
1001 name: String::from(*name),
1002 extends: vec![String::from("cbcl")],
1003 author: None,
1004 performatives: vec![],
1005 resources: ResourceBounds {
1006 max_depth: 8,
1007 max_expansion_size: 512,
1008 },
1009 examples: vec![],
1010 signature: None,
1011 hash: None,
1012 protocol: Some(String::from("ed25519")),
1013 causal_protocol: None,
1014 shapes: Vec::new(),
1015 })
1016 .unwrap();
1017 }
1018 assert_eq!(reg.len(), 4);
1019 assert!(reg.is_well_formed());
1020 }
1021
1022 #[test]
1023 fn registry_iter() {
1024 let reg = DialectRegistry::new();
1025 let names: Vec<&str> = reg.iter().map(|d| d.name.as_str()).collect();
1026 assert_eq!(names, vec!["cbcl-base"]);
1027 }
1028
1029 #[test]
1030 fn registry_default() {
1031 let reg = DialectRegistry::default();
1032 assert!(reg.is_well_formed());
1033 }
1034
1035 use crate::r4::{R4Result, Signer};
1038
1039 struct MockSigner;
1040
1041 impl Signer for MockSigner {
1042 fn sign(&self, _data: &[u8]) -> Vec<u8> {
1043 alloc::vec![0xAA, 0xBB]
1044 }
1045 fn verify(&self, _data: &[u8], sig: &[u8]) -> bool {
1046 sig == [0xAA, 0xBB]
1047 }
1048 }
1049
1050 #[test]
1051 fn registry_install_with_signer_accepts_unsigned() {
1052 let mut reg = DialectRegistry::new();
1053 let d = Dialect {
1054 types: Default::default(),
1055 roles: Vec::new(),
1056 state: None,
1057 state_bounds: None,
1058 causal_locality: Default::default(),
1059 name: String::from("unsigned-dialect"),
1060 extends: vec![],
1061 author: None,
1062 performatives: vec![],
1063 resources: ResourceBounds {
1064 max_depth: 8,
1065 max_expansion_size: 512,
1066 },
1067 examples: vec![],
1068 signature: None,
1069 hash: None,
1070 protocol: None,
1071 causal_protocol: None,
1072 shapes: Vec::new(),
1073 };
1074 let result = reg.install_with_signer(d, &MockSigner).unwrap();
1075 assert_eq!(result, R4Result::Unsigned);
1076 assert_eq!(reg.len(), 2);
1077 }
1078
1079 #[test]
1080 fn registry_install_with_signer_accepts_valid_signature() {
1081 let mut reg = DialectRegistry::new();
1082 let d = Dialect {
1083 types: Default::default(),
1084 roles: Vec::new(),
1085 state: None,
1086 state_bounds: None,
1087 causal_locality: Default::default(),
1088 name: String::from("signed-dialect"),
1089 extends: vec![],
1090 author: None,
1091 performatives: vec![],
1092 resources: ResourceBounds {
1093 max_depth: 8,
1094 max_expansion_size: 512,
1095 },
1096 examples: vec![],
1097 signature: Some(alloc::vec![0xAA, 0xBB]),
1098 hash: None,
1099 protocol: Some(String::from("ed25519")),
1100 causal_protocol: None,
1101 shapes: Vec::new(),
1102 };
1103 let result = reg.install_with_signer(d, &MockSigner).unwrap();
1104 assert_eq!(result, R4Result::Valid);
1105 assert_eq!(reg.len(), 2);
1106 }
1107
1108 #[test]
1109 fn registry_install_with_signer_rejects_invalid_signature() {
1110 let mut reg = DialectRegistry::new();
1111 let d = Dialect {
1112 types: Default::default(),
1113 roles: Vec::new(),
1114 state: None,
1115 state_bounds: None,
1116 causal_locality: Default::default(),
1117 name: String::from("bad-sig-dialect"),
1118 extends: vec![],
1119 author: None,
1120 performatives: vec![],
1121 resources: ResourceBounds {
1122 max_depth: 8,
1123 max_expansion_size: 512,
1124 },
1125 examples: vec![],
1126 signature: Some(alloc::vec![0xFF, 0xFF]),
1127 hash: None,
1128 protocol: Some(String::from("ed25519")),
1129 causal_protocol: None,
1130 shapes: Vec::new(),
1131 };
1132 let err = reg.install_with_signer(d, &MockSigner).unwrap_err();
1133 match err {
1134 DialectInstallError::R4Violation { dialect_name } => {
1135 assert_eq!(dialect_name, "bad-sig-dialect");
1136 }
1137 other => panic!("expected R4Violation, got {:?}", other),
1138 }
1139 assert_eq!(reg.len(), 1);
1141 }
1142
1143 #[test]
1144 fn registry_install_with_signer_still_checks_r1_r2_r3() {
1145 let mut reg = DialectRegistry::new();
1146 let d = Dialect {
1148 types: Default::default(),
1149 roles: Vec::new(),
1150 state: None,
1151 state_bounds: None,
1152 causal_locality: Default::default(),
1153 name: String::from("bad-r3"),
1154 extends: vec![],
1155 author: None,
1156 performatives: vec![PerformativeDef {
1157 role: None,
1158 name: String::from("tell"),
1159 params: vec![],
1160 template: effect_template("custom-tell"),
1161 }],
1162 resources: ResourceBounds {
1163 max_depth: 8,
1164 max_expansion_size: 512,
1165 },
1166 examples: vec![],
1167 signature: Some(alloc::vec![0xAA, 0xBB]),
1168 hash: None,
1169 protocol: None,
1170 causal_protocol: None,
1171 shapes: Vec::new(),
1172 };
1173 let err = reg.install_with_signer(d, &MockSigner).unwrap_err();
1174 assert!(matches!(err, DialectInstallError::R3Violation { .. }));
1175 }
1176
1177 #[test]
1178 fn r4_violation_display() {
1179 let err = DialectInstallError::R4Violation {
1180 dialect_name: String::from("bad"),
1181 };
1182 let msg = alloc::format!("{}", err);
1183 assert!(msg.contains("R4 violation"));
1184 assert!(msg.contains("bad"));
1185 }
1186
1187 struct CanonicalSigner;
1193
1194 impl Signer for CanonicalSigner {
1195 fn sign(&self, data: &[u8]) -> Vec<u8> {
1196 let mut sum: u32 = 0x9e3779b9;
1198 for &b in data {
1199 sum = sum.wrapping_mul(33).wrapping_add(b as u32);
1200 }
1201 sum.to_le_bytes().to_vec()
1202 }
1203 fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
1204 self.sign(data) == sig
1205 }
1206 }
1207
1208 fn signed_dialect_with_protocol_and_shapes() -> Dialect {
1209 use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1210 use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1211 let mut steps = alloc::collections::BTreeMap::new();
1212 steps.insert(
1213 "begin".into(),
1214 StepDecl {
1215 performative: "begin".into(),
1216 predecessors: vec![],
1217 successors: vec![NodeRef::Single("greet".into())],
1218 },
1219 );
1220 steps.insert(
1221 "greet".into(),
1222 StepDecl {
1223 performative: "greet".into(),
1224 predecessors: vec![NodeRef::Single("begin".into())],
1225 successors: vec![],
1226 },
1227 );
1228 Dialect {
1229 types: Default::default(),
1230 roles: Vec::new(),
1231 state: None,
1232 state_bounds: None,
1233 causal_locality: Default::default(),
1234 name: String::from("bound-by-signature"),
1235 extends: vec![String::from("cbcl")],
1236 author: None,
1237 performatives: vec![PerformativeDef {
1238 role: None,
1239 name: String::from("greet"),
1240 params: vec![],
1241 template: SExpr::List(vec![
1242 SExpr::Atom(Atom::Symbol(String::from("effect"))),
1243 SExpr::Atom(Atom::Symbol(String::from("greet-action"))),
1244 ]),
1245 }],
1246 resources: ResourceBounds {
1247 max_depth: 8,
1248 max_expansion_size: 512,
1249 },
1250 examples: vec![],
1251 signature: None,
1252 hash: None,
1253 protocol: None,
1254 causal_protocol: Some(CausalProtocol { steps }),
1255 shapes: vec![ShapeConstraint {
1256 performative: String::from("greet"),
1257 rules: vec![ShapeRule::Require {
1258 keyword: String::from("target"),
1259 type_constraint: Some(TypeConstraint::String),
1260 children: vec![],
1261 }],
1262 }],
1263 }
1264 }
1265
1266 #[test]
1267 fn signed_dialect_with_causal_protocol_now_installs() {
1268 let mut d = signed_dialect_with_protocol_and_shapes();
1271 d.shapes = Vec::new(); let bytes = crate::canonical::dialect_canonical_bytes(&d);
1273 d.signature = Some(CanonicalSigner.sign(&bytes));
1274
1275 let mut reg = DialectRegistry::new();
1276 let result = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1277 assert_eq!(result, R4Result::Valid);
1278 }
1279
1280 #[test]
1281 fn signed_dialect_with_shapes_now_installs() {
1282 let mut d = signed_dialect_with_protocol_and_shapes();
1283 d.causal_protocol = None; let bytes = crate::canonical::dialect_canonical_bytes(&d);
1285 d.signature = Some(CanonicalSigner.sign(&bytes));
1286
1287 let mut reg = DialectRegistry::new();
1288 let result = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1289 assert_eq!(result, R4Result::Valid);
1290 }
1291
1292 #[test]
1293 fn mutating_causal_protocol_invalidates_existing_signature() {
1294 use crate::protocol::{NodeRef, StepDecl};
1295 let original = signed_dialect_with_protocol_and_shapes();
1298 let bytes = crate::canonical::dialect_canonical_bytes(&original);
1299 let sig = CanonicalSigner.sign(&bytes);
1300
1301 let mut tampered = original;
1302 tampered.signature = Some(sig);
1303 if let Some(ref mut p) = tampered.causal_protocol {
1305 p.steps.insert(
1306 "greet".into(),
1307 StepDecl {
1308 performative: "greet".into(),
1309 predecessors: vec![NodeRef::Single("ok".into())],
1310 successors: vec![],
1311 },
1312 );
1313 }
1314
1315 let mut reg = DialectRegistry::new();
1316 let err = reg
1317 .install_with_signer(tampered, &CanonicalSigner)
1318 .unwrap_err();
1319 assert!(
1320 matches!(err, DialectInstallError::R4Violation { .. }),
1321 "expected R4 violation after causal_protocol tamper, got {err:?}"
1322 );
1323 }
1324
1325 #[test]
1326 fn mutating_shapes_invalidates_existing_signature() {
1327 use crate::shape::{ShapeRule, TypeConstraint};
1328 let original = signed_dialect_with_protocol_and_shapes();
1329 let bytes = crate::canonical::dialect_canonical_bytes(&original);
1330 let sig = CanonicalSigner.sign(&bytes);
1331
1332 let mut tampered = original;
1333 tampered.signature = Some(sig);
1334 if let Some(shape) = tampered.shapes.first_mut() {
1336 shape.rules.push(ShapeRule::Require {
1337 keyword: String::from("priority"),
1338 type_constraint: Some(TypeConstraint::Integer),
1339 children: vec![],
1340 });
1341 }
1342
1343 let mut reg = DialectRegistry::new();
1344 let err = reg
1345 .install_with_signer(tampered, &CanonicalSigner)
1346 .unwrap_err();
1347 assert!(
1348 matches!(err, DialectInstallError::R4Violation { .. }),
1349 "expected R4 violation after shapes tamper, got {err:?}"
1350 );
1351 }
1352
1353 #[test]
1356 fn cbcl_shorthand_extends_resolves_to_base_at_install() {
1357 use crate::protocol::{CausalProtocol, NodeRef, StepDecl};
1358 let mut reg = DialectRegistry::new();
1359 let mut steps = alloc::collections::BTreeMap::new();
1363 steps.insert(
1364 "begin".into(),
1365 StepDecl {
1366 performative: "begin".into(),
1367 predecessors: vec![],
1368 successors: vec![NodeRef::Single("ok".into())],
1369 },
1370 );
1371 steps.insert(
1372 "ok".into(),
1373 StepDecl {
1374 performative: "ok".into(),
1375 predecessors: vec![NodeRef::Single("begin".into())],
1376 successors: vec![],
1377 },
1378 );
1379 let d = Dialect {
1380 types: Default::default(),
1381 roles: Vec::new(),
1382 state: None,
1383 state_bounds: None,
1384 causal_locality: Default::default(),
1385 name: String::from("uses-ok"),
1386 extends: vec![String::from("cbcl")],
1387 author: None,
1388 performatives: vec![],
1389 resources: ResourceBounds {
1390 max_depth: 8,
1391 max_expansion_size: 512,
1392 },
1393 examples: vec![],
1394 signature: None,
1395 hash: None,
1396 protocol: None,
1397 causal_protocol: Some(CausalProtocol { steps }),
1398 shapes: Vec::new(),
1399 };
1400 reg.install(d)
1401 .expect("dialect extending cbcl should install");
1402 }
1403
1404 fn hashless_dialect(name: &str) -> Dialect {
1407 Dialect {
1408 types: Default::default(),
1409 roles: Vec::new(),
1410 state: None,
1411 state_bounds: None,
1412 causal_locality: Default::default(),
1413 name: String::from(name),
1414 extends: vec![String::from("cbcl")],
1415 author: Some(String::from("@hash-tests")),
1416 performatives: vec![PerformativeDef {
1417 role: None,
1418 name: String::from("greet"),
1419 params: vec![],
1420 template: effect_template("greet-action"),
1421 }],
1422 resources: ResourceBounds {
1423 max_depth: 8,
1424 max_expansion_size: 512,
1425 },
1426 examples: vec![],
1427 signature: None,
1428 hash: None,
1429 protocol: None,
1430 causal_protocol: None,
1431 shapes: Vec::new(),
1432 }
1433 }
1434
1435 #[test]
1436 fn install_populates_canonical_hash() {
1437 let d = hashless_dialect("hashed");
1438 let expected = crate::canonical::dialect_hash(&d);
1439 let mut reg = DialectRegistry::new();
1440 reg.install(d).unwrap();
1441 let installed = reg.find_by_name("hashed").unwrap();
1442 let h = installed.hash.as_deref().expect("install must set hash");
1443 assert_eq!(h, expected);
1444 let hex = h.strip_prefix("f1220").expect("f1220 prefix");
1445 assert_eq!(hex.len(), 64);
1446 assert!(hex
1447 .chars()
1448 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
1449 }
1450
1451 #[test]
1452 fn install_hash_is_stable_across_registries() {
1453 let mut reg1 = DialectRegistry::new();
1454 let mut reg2 = DialectRegistry::new();
1455 reg1.install(hashless_dialect("stable")).unwrap();
1456 reg2.install(hashless_dialect("stable")).unwrap();
1457 assert_eq!(
1458 reg1.find_by_name("stable").unwrap().hash,
1459 reg2.find_by_name("stable").unwrap().hash
1460 );
1461 }
1462
1463 #[test]
1464 fn install_hash_changes_when_performative_renamed() {
1465 let mut renamed = hashless_dialect("same-name");
1466 renamed.performatives[0].name = String::from("salute");
1467 let mut reg1 = DialectRegistry::new();
1468 let mut reg2 = DialectRegistry::new();
1469 reg1.install(hashless_dialect("same-name")).unwrap();
1470 reg2.install(renamed).unwrap();
1471 assert_ne!(
1472 reg1.find_by_name("same-name").unwrap().hash,
1473 reg2.find_by_name("same-name").unwrap().hash,
1474 "renaming a performative must change the installed hash"
1475 );
1476 }
1477
1478 #[test]
1479 fn install_preserves_declared_hash() {
1480 let mut d = hashless_dialect("claimed");
1483 d.hash = Some(String::from("f1220abcd1234"));
1484 let mut reg = DialectRegistry::new();
1485 reg.install(d).unwrap();
1486 assert_eq!(
1487 reg.find_by_name("claimed").unwrap().hash.as_deref(),
1488 Some("f1220abcd1234")
1489 );
1490 }
1491
1492 #[test]
1493 fn install_with_signer_populates_canonical_hash() {
1494 let d = hashless_dialect("signer-hashed");
1495 let expected = crate::canonical::dialect_hash(&d);
1496 let mut reg = DialectRegistry::new();
1497 reg.install_with_signer(d, &MockSigner).unwrap();
1498 assert_eq!(
1499 reg.find_by_name("signer-hashed").unwrap().hash.as_deref(),
1500 Some(expected.as_str())
1501 );
1502 }
1503
1504 #[test]
1505 fn install_hash_of_signed_dialect_keeps_signature_valid() {
1506 let mut d = hashless_dialect("signed-and-hashed");
1509 d.protocol = Some(String::from("ed25519"));
1510 d.signature = Some(CanonicalSigner.sign(&crate::canonical::dialect_canonical_bytes(&d)));
1511 let mut reg = DialectRegistry::new();
1512 let r4 = reg.install_with_signer(d, &CanonicalSigner).unwrap();
1513 assert_eq!(r4, R4Result::Valid);
1514 assert!(reg
1515 .find_by_name("signed-and-hashed")
1516 .unwrap()
1517 .hash
1518 .is_some());
1519 }
1520}