1use serde::{Deserialize, Serialize};
11use std::collections::{BTreeSet, HashMap};
12
13#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
14pub struct Place {
15 pub id: String,
16}
17
18impl Place {
19 pub fn new(id: impl Into<String>) -> Self {
20 Self { id: id.into() }
21 }
22}
23
24#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize)]
25#[serde(transparent)]
29pub struct Marking {
30 pub tokens: HashMap<String, Vec<String>>,
32}
33
34impl Marking {
35 pub fn new() -> Self {
36 Self::default()
37 }
38
39 pub fn with_token(mut self, color: &str, hash: &str) -> Self {
40 self.tokens
41 .entry(color.to_string())
42 .or_default()
43 .push(hash.to_string());
44 self
45 }
46
47 pub fn restrict(&self, colors: &BTreeSet<String>) -> Self {
49 let mut tokens = HashMap::new();
50 for color in colors {
51 if let Some(vals) = self.tokens.get(color) {
52 tokens.insert(color.clone(), vals.clone());
53 }
54 }
55 Self { tokens }
56 }
57}
58
59#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
60pub struct OpenSet {
61 pub places: BTreeSet<Place>,
62}
63
64impl OpenSet {
65 pub fn new() -> Self {
66 Self::default()
67 }
68
69 pub fn from_places<I: IntoIterator<Item = Place>>(places: I) -> Self {
70 Self {
71 places: places.into_iter().collect(),
72 }
73 }
74
75 pub fn intersection(&self, other: &OpenSet) -> OpenSet {
76 OpenSet {
77 places: self
78 .places
79 .intersection(&other.places)
80 .cloned()
81 .collect(),
82 }
83 }
84
85 pub fn is_disjoint(&self, other: &OpenSet) -> bool {
86 self.places.is_disjoint(&other.places)
87 }
88
89 pub fn is_subset(&self, other: &OpenSet) -> bool {
90 self.places.is_subset(&other.places)
91 }
92
93 pub fn is_empty(&self) -> bool {
94 self.places.is_empty()
95 }
96
97 pub fn colors(&self) -> BTreeSet<String> {
98 self.places.iter().map(|p| p.id.clone()).collect()
100 }
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct Section {
105 pub open_set: OpenSet,
106 pub marking: Marking,
107}
108
109impl Section {
110 pub fn new(open_set: OpenSet, marking: Marking) -> Self {
111 Self { open_set, marking }
112 }
113
114 pub fn restrict(&self, subset: &OpenSet) -> Result<Section, CohomologyError> {
116 if !subset.is_subset(&self.open_set) {
117 return Err(CohomologyError::InvalidRestriction {
118 subset: subset.clone(),
119 superset: self.open_set.clone(),
120 });
121 }
122 let colors = subset.colors();
123 let marking = self.marking.restrict(&colors);
124 Ok(Section {
125 open_set: subset.clone(),
126 marking,
127 })
128 }
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct Sheaf {
133 pub sections: HashMap<OpenSet, Section>,
134}
135
136impl Default for Sheaf {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl Sheaf {
143 pub fn new() -> Self {
144 Self {
145 sections: HashMap::new(),
146 }
147 }
148
149 pub fn restriction(&self, section: &Section, subset: &OpenSet) -> Result<Section, CohomologyError> {
151 section.restrict(subset)
152 }
153
154 pub fn gluing_check(
161 &self,
162 local_sections: &[Section],
163 open_cover: &[OpenSet],
164 ) -> Result<Section, CohomologyError> {
165 if local_sections.len() != open_cover.len() {
166 return Err(CohomologyError::InputMismatch);
167 }
168 if local_sections.is_empty() {
169 return Ok(Section::new(OpenSet::new(), Marking::new()));
170 }
171
172 let merkle_trees: Vec<MerkleNode> =
174 local_sections.iter().map(section_to_merkle).collect();
175
176 let n = local_sections.len();
177 for i in 0..n {
178 for j in (i + 1)..n {
179 let intersection = open_cover[i].intersection(&open_cover[j]);
180 if intersection.is_empty() {
181 continue;
182 }
183 let root_i = merkle_sub_root(&merkle_trees[i], &intersection.places);
185 let root_j = merkle_sub_root(&merkle_trees[j], &intersection.places);
186 if root_i != root_j {
187 let left = self.restriction(&local_sections[i], &intersection)?;
191 let right = self.restriction(&local_sections[j], &intersection)?;
192 return Err(CohomologyError::GluingFailure {
193 place_i: local_sections[i].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
194 place_j: local_sections[j].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
195 intersection: intersection.clone(),
196 expected_marking: left.marking,
197 actual_marking: right.marking,
198 cohomology_class: "[delta_s]".to_string(),
199 });
200 }
201 }
202 }
203
204 let mut union = OpenSet::new();
205 let mut marking = Marking::new();
206 for (section, cover) in local_sections.iter().zip(open_cover.iter()) {
207 union.places.extend(cover.places.iter().cloned());
208 for (color, vals) in §ion.marking.tokens {
210 marking.tokens.insert(color.clone(), vals.clone());
211 }
212 }
213 Ok(Section::new(union, marking))
214 }
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218pub enum CohomologyError {
219 InputMismatch,
220 InvalidRestriction { subset: OpenSet, superset: OpenSet },
221 GluingFailure {
222 place_i: Place,
223 place_j: Place,
224 intersection: OpenSet,
225 expected_marking: Marking,
226 actual_marking: Marking,
227 cohomology_class: String,
228 },
229}
230
231impl std::fmt::Display for CohomologyError {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 match self {
234 CohomologyError::InputMismatch => write!(f, "open cover and local sections have different lengths"),
235 CohomologyError::InvalidRestriction { subset, superset } => {
236 write!(f, "cannot restrict {:?} to subset {:?}", superset, subset)
237 }
238 CohomologyError::GluingFailure { place_i, place_j, intersection, .. } => {
239 write!(
240 f,
241 "COHOMOLOGICAL OBSTRUCTION: Sections disagree on intersection of {:?} and {:?}: {:?}",
242 place_i.id, place_j.id, intersection
243 )
244 }
245 }
246 }
247}
248
249impl std::error::Error for CohomologyError {}
250
251#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct MerkleNode {
258 pub hash: [u8; 32],
259 pub children: Vec<MerkleNode>,
260 pub place_id: Option<String>,
261 pub payload: Option<Vec<u8>>,
262}
263
264pub fn compute_merkle_root(payload: &[u8]) -> [u8; 32] {
266 crate::hash::raw_hash_bytes_32(payload)
267}
268
269pub fn compute_merkle_node(children: &[MerkleNode]) -> [u8; 32] {
272 let mut combined = Vec::new();
273 for child in children {
274 combined.extend_from_slice(&child.hash);
275 }
276 crate::hash::raw_hash_bytes_32(&combined)
277}
278
279pub fn section_to_merkle(section: &Section) -> MerkleNode {
283 let mut leaves: Vec<MerkleNode> = section
284 .open_set
285 .places
286 .iter()
287 .map(|place| {
288 let tokens = section.marking.tokens.get(&place.id);
289 let payload = match tokens {
290 Some(vals) => format!("{}:{}", place.id, vals.join(",")),
291 None => place.id.clone(),
292 };
293 let hash = compute_merkle_root(payload.as_bytes());
294 MerkleNode {
295 hash,
296 children: vec![],
297 place_id: Some(place.id.clone()),
298 payload: Some(payload.into_bytes()),
299 }
300 })
301 .collect();
302 leaves.sort_by(|a, b| a.place_id.cmp(&b.place_id));
303 let root_hash = compute_merkle_node(&leaves);
304 MerkleNode {
305 hash: root_hash,
306 children: leaves,
307 place_id: None,
308 payload: None,
309 }
310}
311
312pub fn merkle_sub_root(node: &MerkleNode, places: &BTreeSet<Place>) -> [u8; 32] {
316 let place_ids: BTreeSet<String> = places.iter().map(|p| p.id.clone()).collect();
317 let matching: Vec<&MerkleNode> = node
318 .children
319 .iter()
320 .filter(|c| {
321 c.place_id
322 .as_ref()
323 .map(|id| place_ids.contains(id))
324 .unwrap_or(false)
325 })
326 .collect();
327 if matching.is_empty() {
328 return [0u8; 32];
329 }
330 let mut combined = Vec::new();
331 for child in &matching {
332 combined.extend_from_slice(&child.hash);
333 }
334 crate::hash::raw_hash_bytes_32(&combined)
335}
336
337#[cfg(feature = "native")]
339pub fn store_section_merkle(
340 section: &Section,
341 conn: &rusqlite::Connection,
342) -> Result<[u8; 32], String> {
343 let node = section_to_merkle(section);
344 let yaml = serde_yaml::to_string(section).map_err(|e| e.to_string())?;
345 let hash_hex = hex::encode(node.hash);
346 let now = crate::fs_utils::compute_g_time();
348 conn.execute(
349 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
350 rusqlite::params![hash_hex, yaml, now],
351 )
352 .map_err(|e| e.to_string())?;
353 Ok(node.hash)
354}
355
356#[cfg(feature = "native")]
358pub fn load_section_merkle(
359 hash: &[u8; 32],
360 conn: &rusqlite::Connection,
361) -> Result<Section, String> {
362 let hash_hex = hex::encode(hash);
363 let content: String = conn
364 .query_row(
365 "SELECT content FROM card WHERE hash = ?",
366 [&hash_hex],
367 |row| row.get(0),
368 )
369 .map_err(|e| format!("Failed to load section: {}", e))?;
370 serde_yaml::from_str(&content).map_err(|e| format!("Failed to deserialize section: {}", e))
371}
372
373#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct CohomologyConflictReport {
381 pub conflicting_places: (Place, Place),
382 pub intersection: OpenSet,
383 pub expected_marking: Marking,
384 pub actual_marking: Marking,
385 pub cohomology_class: String,
386 pub timestamp: String,
387 pub agent_dids: Vec<String>,
388}
389
390impl CohomologyConflictReport {
391 pub fn to_yaml(&self) -> String {
393 serde_yaml::to_string(self).unwrap_or_else(|_| "cohomology_conflict: <error>".to_string())
394 }
395
396 pub fn content_hash(&self) -> String {
398 crate::hash::raw_hash_string(&self.to_yaml())
399 }
400
401 pub fn from_error(
403 err: &CohomologyError,
404 agent_dids: Vec<String>,
405 ) -> Option<Self> {
406 match err {
407 CohomologyError::GluingFailure {
408 place_i,
409 place_j,
410 intersection,
411 expected_marking,
412 actual_marking,
413 cohomology_class,
414 } => Some(CohomologyConflictReport {
415 conflicting_places: (place_i.clone(), place_j.clone()),
416 intersection: intersection.clone(),
417 expected_marking: expected_marking.clone(),
418 actual_marking: actual_marking.clone(),
419 cohomology_class: cohomology_class.clone(),
420 timestamp: chrono::Utc::now().to_rfc3339(),
421 agent_dids,
422 }),
423 _ => None,
424 }
425 }
426}
427
428#[cfg(feature = "native")]
430pub fn store_conflict_report(
431 report: &CohomologyConflictReport,
432 conn: &rusqlite::Connection,
433) -> Result<String, String> {
434 let yaml = report.to_yaml();
435 let hash = report.content_hash();
436 let now = crate::fs_utils::compute_g_time();
438 conn.execute(
439 "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
440 rusqlite::params![hash, yaml, now],
441 )
442 .map_err(|e| e.to_string())?;
443 Ok(hash)
444}
445
446#[cfg(test)]
447#[path = "sheaf_tests.rs"]
448mod tests;