use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap};
#[cfg(feature = "native")]
pub use crate::cpn::mcard_token::PlaceMCard;
#[cfg(feature = "native")]
pub use crate::cpn::token_namespace::MCardMarking;
#[cfg(not(feature = "native"))]
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct PlaceMCard {
pub place_id: String,
pub role: String,
pub color_type: String,
}
#[cfg(not(feature = "native"))]
impl PlaceMCard {
pub fn new(id: impl Into<String>) -> Self {
Self {
place_id: id.into(),
role: "Ordinary".into(),
color_type: "unit".into(),
}
}
}
#[cfg(not(feature = "native"))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardMarking {
pub by_place: std::collections::BTreeMap<String, Vec<String>>,
}
#[cfg(not(feature = "native"))]
impl MCardMarking {
pub fn new() -> Self {
Self::default()
}
pub fn restrict(&self, colors: &BTreeSet<String>) -> Self {
let mut by_place = std::collections::BTreeMap::new();
for (p, toks) in &self.by_place {
if colors.contains(p) {
by_place.insert(p.clone(), toks.clone());
}
}
Self { by_place }
}
}
pub type Marking = MCardMarking;
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Place {
pub id: String,
}
impl Place {
pub fn new(id: impl Into<String>) -> Self {
Self { id: id.into() }
}
pub fn to_mcard(&self) -> PlaceMCard {
PlaceMCard::new(&self.id)
}
pub fn from_mcard(mcard: &PlaceMCard) -> Self {
Self { id: mcard.place_id.clone() }
}
}
impl From<PlaceMCard> for Place {
fn from(m: PlaceMCard) -> Self {
Self { id: m.place_id.clone() }
}
}
impl From<&PlaceMCard> for Place {
fn from(m: &PlaceMCard) -> Self {
Self { id: m.place_id.clone() }
}
}
impl From<Place> for PlaceMCard {
fn from(p: Place) -> Self {
PlaceMCard::new(p.id)
}
}
impl From<&Place> for PlaceMCard {
fn from(p: &Place) -> Self {
PlaceMCard::new(&p.id)
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct OpenSet {
pub places: BTreeSet<Place>,
}
impl OpenSet {
pub fn new() -> Self {
Self::default()
}
pub fn from_places<I: IntoIterator<Item = Place>>(places: I) -> Self {
Self {
places: places.into_iter().collect(),
}
}
pub fn intersection(&self, other: &OpenSet) -> OpenSet {
OpenSet {
places: self
.places
.intersection(&other.places)
.cloned()
.collect(),
}
}
pub fn is_disjoint(&self, other: &OpenSet) -> bool {
self.places.is_disjoint(&other.places)
}
pub fn is_subset(&self, other: &OpenSet) -> bool {
self.places.is_subset(&other.places)
}
pub fn is_empty(&self) -> bool {
self.places.is_empty()
}
pub fn colors(&self) -> BTreeSet<String> {
self.places.iter().map(|p| p.id.clone()).collect()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Section {
pub open_set: OpenSet,
pub marking: Marking,
}
impl Section {
pub fn new(open_set: OpenSet, marking: Marking) -> Self {
Self { open_set, marking }
}
pub fn restrict(&self, subset: &OpenSet) -> Result<Section, CohomologyError> {
if !subset.is_subset(&self.open_set) {
return Err(CohomologyError::InvalidRestriction {
subset: subset.clone(),
superset: self.open_set.clone(),
});
}
let colors = subset.colors();
let marking = self.marking.restrict(&colors);
Ok(Section {
open_set: subset.clone(),
marking,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sheaf {
pub sections: HashMap<OpenSet, Section>,
}
impl Default for Sheaf {
fn default() -> Self {
Self::new()
}
}
impl Sheaf {
pub fn new() -> Self {
Self {
sections: HashMap::new(),
}
}
pub fn restriction(&self, section: &Section, subset: &OpenSet) -> Result<Section, CohomologyError> {
section.restrict(subset)
}
pub fn gluing_check(
&self,
local_sections: &[Section],
open_cover: &[OpenSet],
) -> Result<Section, CohomologyError> {
if local_sections.len() != open_cover.len() {
return Err(CohomologyError::InputMismatch);
}
if local_sections.is_empty() {
return Ok(Section::new(OpenSet::new(), Marking::new()));
}
let merkle_trees: Vec<MerkleNode> =
local_sections.iter().map(section_to_merkle).collect();
let n = local_sections.len();
for i in 0..n {
for j in (i + 1)..n {
let intersection = open_cover[i].intersection(&open_cover[j]);
if intersection.is_empty() {
continue;
}
let root_i = merkle_sub_root(&merkle_trees[i], &intersection.places);
let root_j = merkle_sub_root(&merkle_trees[j], &intersection.places);
if root_i != root_j {
let left = self.restriction(&local_sections[i], &intersection)?;
let right = self.restriction(&local_sections[j], &intersection)?;
return Err(CohomologyError::GluingFailure {
place_i: local_sections[i].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
place_j: local_sections[j].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
intersection: intersection.clone(),
expected_marking: left.marking,
actual_marking: right.marking,
cohomology_class: "[delta_s]".to_string(),
});
}
}
}
let mut union = OpenSet::new();
let mut marking = Marking::new();
for (section, cover) in local_sections.iter().zip(open_cover.iter()) {
union.places.extend(cover.places.iter().cloned());
for (color, vals) in §ion.marking.by_place {
marking.by_place.insert(color.clone(), vals.clone());
}
}
Ok(Section::new(union, marking))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CohomologyError {
InputMismatch,
InvalidRestriction { subset: OpenSet, superset: OpenSet },
GluingFailure {
place_i: Place,
place_j: Place,
intersection: OpenSet,
expected_marking: Marking,
actual_marking: Marking,
cohomology_class: String,
},
}
impl std::fmt::Display for CohomologyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CohomologyError::InputMismatch => write!(f, "open cover and local sections have different lengths"),
CohomologyError::InvalidRestriction { subset, superset } => {
write!(f, "cannot restrict {:?} to subset {:?}", superset, subset)
}
CohomologyError::GluingFailure { place_i, place_j, intersection, .. } => {
write!(
f,
"COHOMOLOGICAL OBSTRUCTION: Sections disagree on intersection of {:?} and {:?}: {:?}",
place_i.id, place_j.id, intersection
)
}
}
}
}
impl std::error::Error for CohomologyError {}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MerkleNode {
pub hash: [u8; 32],
pub children: Vec<MerkleNode>,
pub place_id: Option<String>,
pub payload: Option<Vec<u8>>,
}
pub fn compute_merkle_root(payload: &[u8]) -> [u8; 32] {
crate::hash::raw_hash_bytes_32(payload)
}
pub fn compute_merkle_node(children: &[MerkleNode]) -> [u8; 32] {
let mut combined = Vec::new();
for child in children {
combined.extend_from_slice(&child.hash);
}
crate::hash::raw_hash_bytes_32(&combined)
}
pub fn section_to_merkle(section: &Section) -> MerkleNode {
let mut leaves: Vec<MerkleNode> = section
.open_set
.places
.iter()
.map(|place| {
let tokens = section.marking.by_place.get(&place.id);
let payload = match tokens {
Some(vals) => format!("{}:{}", place.id, vals.join(",")),
None => place.id.clone(),
};
let hash = compute_merkle_root(payload.as_bytes());
MerkleNode {
hash,
children: vec![],
place_id: Some(place.id.clone()),
payload: Some(payload.into_bytes()),
}
})
.collect();
leaves.sort_by(|a, b| a.place_id.cmp(&b.place_id));
let root_hash = compute_merkle_node(&leaves);
MerkleNode {
hash: root_hash,
children: leaves,
place_id: None,
payload: None,
}
}
pub fn merkle_sub_root(node: &MerkleNode, places: &BTreeSet<Place>) -> [u8; 32] {
let place_ids: BTreeSet<String> = places.iter().map(|p| p.id.clone()).collect();
let matching: Vec<&MerkleNode> = node
.children
.iter()
.filter(|c| {
c.place_id
.as_ref()
.map(|id| place_ids.contains(id))
.unwrap_or(false)
})
.collect();
if matching.is_empty() {
return [0u8; 32];
}
let mut combined = Vec::new();
for child in &matching {
combined.extend_from_slice(&child.hash);
}
crate::hash::raw_hash_bytes_32(&combined)
}
#[cfg(feature = "native")]
pub use crate::layer2::sheaf_persistence::{load_section_merkle, store_section_merkle};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohomologyConflictReport {
pub conflicting_places: (Place, Place),
pub intersection: OpenSet,
pub expected_marking: Marking,
pub actual_marking: Marking,
pub cohomology_class: String,
pub timestamp: String,
pub agent_dids: Vec<String>,
}
impl CohomologyConflictReport {
pub fn to_yaml(&self) -> String {
serde_yaml::to_string(self).unwrap_or_else(|_| "cohomology_conflict: <error>".to_string())
}
pub fn content_hash(&self) -> String {
crate::hash::raw_hash_string(&self.to_yaml())
}
pub fn from_error(
err: &CohomologyError,
agent_dids: Vec<String>,
) -> Option<Self> {
match err {
CohomologyError::GluingFailure {
place_i,
place_j,
intersection,
expected_marking,
actual_marking,
cohomology_class,
} => Some(CohomologyConflictReport {
conflicting_places: (place_i.clone(), place_j.clone()),
intersection: intersection.clone(),
expected_marking: expected_marking.clone(),
actual_marking: actual_marking.clone(),
cohomology_class: cohomology_class.clone(),
timestamp: chrono::Utc::now().to_rfc3339(),
agent_dids,
}),
_ => None,
}
}
}
#[cfg(feature = "native")]
pub use crate::layer2::sheaf_persistence::store_conflict_report;
#[cfg(test)]
#[path = "sheaf_tests.rs"]
mod tests;