1use core::fmt;
2use core::str::FromStr;
3use std::collections::{BTreeMap, BTreeSet};
4
5use gitiverse_core::ids::{ActorId, RepoId, serde_hex_bytes, serde_identity_key};
6use gitiverse_git::canonical::canonical_json_bytes;
7use gitiverse_git::{GitError, GitObjectKind, GitStore, Oid, validate_ref_name};
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use sha2::{Digest, Sha256};
10use thiserror::Error;
11use wire_mesh_core::ports::{CoreError, Identity};
12use wire_mesh_wire::DecodeError;
13use wire_mesh_wire::identity::IdentityKey;
14use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
15use wire_mesh_wire::strict;
16use wire_mesh_wire::value::CdeMapBuilder;
17
18const OP_ID_BYTE_LEN: usize = 32;
19const OP_ID_HEX_LEN: usize = OP_ID_BYTE_LEN * 2;
20
21#[derive(Debug, Error)]
23pub enum CobError {
24 #[error("invalid operation id {0:?}")]
25 InvalidOpId(String),
26 #[error("canonical serialisation error: {0}")]
27 Canonical(#[from] gitiverse_git::canonical::CanonicalError),
28 #[error("JSON error: {0}")]
29 Json(#[from] serde_json::Error),
30 #[error("Git store error: {0}")]
31 Git(#[from] GitError),
32 #[error("cryptographic port error: {0}")]
33 Crypto(#[from] CoreError),
34 #[error("author key does not match claimed author actor id")]
35 AuthorKeyMismatch,
36 #[error("operation signature does not verify")]
37 BadSignature,
38 #[error("operation belongs to repo {found}, expected {expected}")]
39 RepoMismatch { expected: RepoId, found: RepoId },
40 #[error("operation has kind {found:?}, expected {expected:?}")]
41 KindMismatch { expected: String, found: String },
42 #[error("invalid operation: {0}")]
43 InvalidOp(String),
44 #[error("missing causal parent {parent} referenced by operation {op_id}")]
45 MissingParent { op_id: OpId, parent: OpId },
46 #[error(
47 "invalid lamport clock on operation {op_id}: {lamport} must exceed parent lamport {parent_lamport}"
48 )]
49 InvalidLamport {
50 op_id: OpId,
51 lamport: u64,
52 parent_lamport: u64,
53 },
54 #[error("cycle detected in operation DAG")]
55 CycleDetected,
56 #[error("actor {actor} is not authorised for operation {op_id}: {reason}")]
57 Unauthorised {
58 actor: ActorId,
59 op_id: OpId,
60 reason: String,
61 },
62 #[error("corrupted COB snapshot blob: expected blob object")]
63 UnexpectedGitObjectKind,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68pub struct OpId(pub [u8; OP_ID_BYTE_LEN]);
69
70impl OpId {
71 #[must_use]
72 pub const fn from_bytes(bytes: [u8; OP_ID_BYTE_LEN]) -> Self {
73 Self(bytes)
74 }
75
76 #[must_use]
77 pub const fn as_bytes(&self) -> &[u8; OP_ID_BYTE_LEN] {
78 &self.0
79 }
80
81 #[must_use]
82 pub fn to_hex(&self) -> String {
83 hex::encode(self.0)
84 }
85
86 pub fn from_hex(s: &str) -> Result<Self, CobError> {
87 if s.len() != OP_ID_HEX_LEN
88 || !s
89 .bytes()
90 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
91 {
92 return Err(CobError::InvalidOpId(s.to_owned()));
93 }
94 let bytes = hex::decode(s).map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
95 let arr: [u8; OP_ID_BYTE_LEN] = bytes
96 .try_into()
97 .map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
98 Ok(Self(arr))
99 }
100}
101
102impl fmt::Display for OpId {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.write_str(&self.to_hex())
105 }
106}
107
108impl FromStr for OpId {
109 type Err = CobError;
110
111 fn from_str(s: &str) -> Result<Self, Self::Err> {
112 Self::from_hex(s)
113 }
114}
115
116impl Serialize for OpId {
117 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
118 serializer.collect_str(self)
119 }
120}
121
122impl<'de> Deserialize<'de> for OpId {
123 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
124 let s = String::deserialize(deserializer)?;
125 Self::from_str(&s).map_err(serde::de::Error::custom)
126 }
127}
128
129impl Encode<()> for OpId {
130 fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
131 &self,
132 e: &mut Encoder<W>,
133 _ctx: &mut (),
134 ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
135 e.bytes(&self.0)?.ok()
136 }
137}
138
139impl Decode<'_, ()> for OpId {
140 fn decode(
141 d: &mut Decoder<'_>,
142 _ctx: &mut (),
143 ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
144 let bytes =
145 strict::bytes_value(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)?;
146 let arr: [u8; OP_ID_BYTE_LEN] = bytes.try_into().map_err(|v: Vec<u8>| {
147 wire_mesh_wire::minicbor::decode::Error::custom(DecodeError::InvalidLength {
148 field: "op-id",
149 expected: OP_ID_BYTE_LEN,
150 found: v.len(),
151 })
152 })?;
153 Ok(Self(arr))
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159pub struct DagOp<T> {
160 pub repo_id: RepoId,
161 pub kind: String,
162 pub author: ActorId,
163 #[serde(with = "serde_identity_key")]
164 pub author_key: IdentityKey,
165 pub parents: Vec<OpId>,
166 pub lamport: u64,
167 pub timestamp: u64,
168 pub payload: T,
169 #[serde(with = "serde_hex_bytes")]
170 pub signature: Vec<u8>,
171}
172
173impl<T: Serialize> DagOp<T> {
174 pub async fn sign_new(
176 repo_id: RepoId,
177 kind: impl Into<String>,
178 mut parents: Vec<OpId>,
179 lamport: u64,
180 timestamp: u64,
181 payload: T,
182 identity: &dyn Identity,
183 ) -> Result<Self, CobError> {
184 let kind = kind.into();
185 if kind.is_empty() {
186 return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
187 }
188 if lamport == 0 {
189 return Err(CobError::InvalidOp(
190 "lamport clock must be at least 1".to_owned(),
191 ));
192 }
193 parents.sort();
194 parents.dedup();
195 let mut op = Self {
196 repo_id,
197 kind,
198 author: ActorId(*identity.device_id()),
199 author_key: identity.identity_key().clone(),
200 parents,
201 lamport,
202 timestamp,
203 payload,
204 signature: Vec::new(),
205 };
206 let signing = op.signing_bytes()?;
207 op.signature = identity.sign(&signing).await?;
208 Ok(op)
209 }
210
211 pub fn signing_bytes(&self) -> Result<Vec<u8>, CobError> {
213 let payload_json = canonical_json_bytes(&self.payload)?;
214 let mut parents_buf = Vec::new();
215 {
216 let mut pe = Encoder::new(&mut parents_buf);
217 let _ = pe.array(self.parents.len() as u64);
218 for parent in &self.parents {
219 let _ = parent.encode(&mut pe, &mut ());
220 }
221 }
222 let mut builder = CdeMapBuilder::new();
223 builder.push("domain", "gitiverse.cob.op-sign.v1");
224 builder.push("repo-id", &self.repo_id);
225 builder.push("kind", &self.kind.as_str());
226 builder.push("author", &self.author);
227 builder.push("author-key", &self.author_key);
228 builder.push_raw(encoded_key("parents"), parents_buf);
229 builder.push("lamport", &self.lamport);
230 builder.push("timestamp", &self.timestamp);
231 builder.push_bytes("payload", &payload_json);
232
233 let mut buf = Vec::new();
234 let mut enc = Encoder::new(&mut buf);
235 let _ = builder.write(&mut enc);
236 Ok(buf)
237 }
238
239 pub fn op_id(&self) -> Result<OpId, CobError> {
241 let signing = self.signing_bytes()?;
242 let mut builder = CdeMapBuilder::new();
243 builder.push("domain", "gitiverse.cob.op-id.v1");
244 builder.push_bytes("signing", &signing);
245 builder.push_bytes("signature", &self.signature);
246 let mut buf = Vec::new();
247 let mut enc = Encoder::new(&mut buf);
248 let _ = builder.write(&mut enc);
249 let digest = Sha256::digest(&buf);
250 Ok(OpId(digest.into()))
251 }
252
253 pub async fn verify(
255 &self,
256 identity: &dyn Identity,
257 expected_repo_id: Option<&RepoId>,
258 expected_kind: Option<&str>,
259 ) -> Result<OpId, CobError> {
260 if let Some(expected) = expected_repo_id
261 && &self.repo_id != expected
262 {
263 return Err(CobError::RepoMismatch {
264 expected: *expected,
265 found: self.repo_id,
266 });
267 }
268 if let Some(expected) = expected_kind
269 && self.kind != expected
270 {
271 return Err(CobError::KindMismatch {
272 expected: expected.to_owned(),
273 found: self.kind.clone(),
274 });
275 }
276 self.validate_structure()?;
277 if ActorId(identity.derive_device_id(&self.author_key.public_key)) != self.author {
278 return Err(CobError::AuthorKeyMismatch);
279 }
280 let signing = self.signing_bytes()?;
281 let ok = identity
282 .verify(&self.author_key, &signing, &self.signature)
283 .await?;
284 if !ok {
285 return Err(CobError::BadSignature);
286 }
287 self.op_id()
288 }
289
290 pub(crate) fn validate_structure(&self) -> Result<(), CobError> {
291 if self.kind.is_empty() {
292 return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
293 }
294 if self.lamport == 0 {
295 return Err(CobError::InvalidOp(
296 "lamport clock must be at least 1".to_owned(),
297 ));
298 }
299 if !self.parents.windows(2).all(|pair| pair[0] < pair[1]) {
300 return Err(CobError::InvalidOp(
301 "operation parents must be strictly ascending and unique".to_owned(),
302 ));
303 }
304 Ok(())
305 }
306}
307
308fn encoded_key(key: &str) -> Vec<u8> {
309 let mut buf = Vec::new();
310 let _ = Encoder::new(&mut buf).str(key);
311 buf
312}
313
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct Dag<T> {
317 ops: BTreeMap<OpId, DagOp<T>>,
318}
319
320impl<T> Default for Dag<T> {
321 fn default() -> Self {
322 Self {
323 ops: BTreeMap::new(),
324 }
325 }
326}
327
328impl<T: Serialize> Dag<T> {
329 #[must_use]
330 pub fn new() -> Self {
331 Self::default()
332 }
333
334 #[must_use]
335 pub fn len(&self) -> usize {
336 self.ops.len()
337 }
338
339 #[must_use]
340 pub fn is_empty(&self) -> bool {
341 self.ops.is_empty()
342 }
343
344 #[must_use]
345 pub fn get(&self, id: &OpId) -> Option<&DagOp<T>> {
346 self.ops.get(id)
347 }
348
349 #[must_use]
350 pub fn contains(&self, id: &OpId) -> bool {
351 self.ops.contains_key(id)
352 }
353
354 #[must_use]
356 pub fn ops(&self) -> &BTreeMap<OpId, DagOp<T>> {
357 &self.ops
358 }
359
360 #[must_use]
362 pub fn next_lamport(&self, parents: &[OpId]) -> u64 {
363 parents
364 .iter()
365 .filter_map(|p| self.ops.get(p).map(|op| op.lamport))
366 .max()
367 .unwrap_or(0)
368 + 1
369 }
370
371 pub async fn insert_verified(
373 &mut self,
374 op: DagOp<T>,
375 identity: &dyn Identity,
376 expected_repo_id: Option<&RepoId>,
377 expected_kind: Option<&str>,
378 ) -> Result<OpId, CobError> {
379 let id = op.verify(identity, expected_repo_id, expected_kind).await?;
380 self.ops.entry(id).or_insert(op);
381 Ok(id)
382 }
383
384 pub fn insert_unchecked(&mut self, op: DagOp<T>) -> Result<OpId, CobError> {
386 op.validate_structure()?;
387 let id = op.op_id()?;
388 self.ops.entry(id).or_insert(op);
389 Ok(id)
390 }
391
392 #[must_use]
394 pub fn tips(&self) -> Vec<OpId> {
395 let mut referenced = BTreeSet::new();
396 for op in self.ops.values() {
397 for parent in &op.parents {
398 referenced.insert(*parent);
399 }
400 }
401 self.ops
402 .keys()
403 .copied()
404 .filter(|id| !referenced.contains(id))
405 .collect()
406 }
407
408 pub fn topological_order(&self) -> Result<Vec<(OpId, &DagOp<T>)>, CobError> {
410 let mut in_degree: BTreeMap<OpId, usize> = BTreeMap::new();
411 let mut children: BTreeMap<OpId, Vec<OpId>> = BTreeMap::new();
412
413 for (id, op) in &self.ops {
414 op.validate_structure()?;
415 for parent_id in &op.parents {
416 let Some(parent_op) = self.ops.get(parent_id) else {
417 return Err(CobError::MissingParent {
418 op_id: *id,
419 parent: *parent_id,
420 });
421 };
422 if op.lamport <= parent_op.lamport {
423 return Err(CobError::InvalidLamport {
424 op_id: *id,
425 lamport: op.lamport,
426 parent_lamport: parent_op.lamport,
427 });
428 }
429 children.entry(*parent_id).or_default().push(*id);
430 }
431 in_degree.insert(*id, op.parents.len());
432 }
433
434 let mut ready: BTreeSet<(u64, OpId)> = BTreeSet::new();
436 for (id, deg) in &in_degree {
437 if *deg == 0
438 && let Some(op) = self.ops.get(id)
439 {
440 ready.insert((op.lamport, *id));
441 }
442 }
443
444 let mut ordered = Vec::with_capacity(self.ops.len());
445 while let Some((_, id)) = ready.pop_first() {
446 let Some(op) = self.ops.get(&id) else {
447 continue;
448 };
449 ordered.push((id, op));
450 if let Some(kids) = children.get(&id) {
451 for kid_id in kids {
452 if let Some(deg) = in_degree.get_mut(kid_id) {
453 *deg -= 1;
454 if *deg == 0
455 && let Some(kid_op) = self.ops.get(kid_id)
456 {
457 ready.insert((kid_op.lamport, *kid_id));
458 }
459 }
460 }
461 }
462 }
463
464 if ordered.len() != self.ops.len() {
465 return Err(CobError::CycleDetected);
466 }
467 Ok(ordered)
468 }
469
470 pub fn fold<S, F>(&self, mut state: S, mut step: F) -> Result<S, CobError>
472 where
473 F: FnMut(&mut S, OpId, &DagOp<T>, &BTreeSet<OpId>) -> Result<(), CobError>,
474 {
475 let ordered = self.topological_order()?;
476 let mut ancestors: BTreeMap<OpId, BTreeSet<OpId>> = BTreeMap::new();
477 for (id, op) in ordered {
478 let mut op_ancestors = BTreeSet::new();
479 for parent_id in &op.parents {
480 op_ancestors.insert(*parent_id);
481 if let Some(parent_ancestors) = ancestors.get(parent_id) {
482 op_ancestors.extend(parent_ancestors.iter().copied());
483 }
484 }
485 step(&mut state, id, op, &op_ancestors)?;
486 ancestors.insert(id, op_ancestors);
487 }
488 Ok(state)
489 }
490}
491
492#[derive(Debug, Clone)]
494pub(crate) struct Lww<T> {
495 pub(crate) clock: (u64, OpId),
496 pub(crate) value: T,
497}
498
499impl<T> Lww<T> {
500 pub(crate) fn new(lamport: u64, op_id: OpId, value: T) -> Self {
501 Self {
502 clock: (lamport, op_id),
503 value,
504 }
505 }
506
507 pub(crate) fn update(&mut self, lamport: u64, op_id: OpId, value: T) {
508 let candidate = (lamport, op_id);
509 if candidate > self.clock {
510 self.clock = candidate;
511 self.value = value;
512 }
513 }
514}
515
516pub(crate) fn require_root<'a, T>(
517 state: &'a mut Option<T>,
518 kind: &str,
519 op_id: OpId,
520) -> Result<&'a mut T, CobError> {
521 state.as_mut().ok_or_else(|| {
522 CobError::InvalidOp(format!("{kind} operation {op_id} arrived before root op"))
523 })
524}
525
526pub fn cob_ref_name(kind: &str, id: &str) -> Result<String, CobError> {
528 if kind.is_empty()
529 || id.is_empty()
530 || kind.contains('/')
531 || id.contains('/')
532 || kind.contains("..")
533 || id.contains("..")
534 {
535 return Err(CobError::InvalidOp(format!(
536 "invalid COB ref components kind={kind:?}, id={id:?}"
537 )));
538 }
539 let ref_name = format!("refs/cobs/{kind}/{id}");
540 validate_ref_name(&ref_name)?;
541 Ok(ref_name)
542}
543
544#[derive(Debug, Serialize)]
545struct CobBlobWriteEnvelope<'a, T> {
546 version: u32,
547 ops: Vec<&'a DagOp<T>>,
548}
549
550#[derive(Debug, Deserialize)]
551struct CobBlobEnvelope<T> {
552 version: u32,
553 ops: Vec<DagOp<T>>,
554}
555
556pub async fn save_dag_to_git<T: Serialize>(
558 store: &dyn GitStore,
559 kind: &str,
560 id: &str,
561 dag: &Dag<T>,
562 expected_old_oid: Option<&Oid>,
563) -> Result<Oid, CobError> {
564 let ref_name = cob_ref_name(kind, id)?;
565 let ops: Vec<&DagOp<T>> = dag.ops().values().collect();
566 let envelope = CobBlobWriteEnvelope { version: 1, ops };
567 let blob_bytes = canonical_json_bytes(&envelope)?;
568 let blob_oid = store.write_blob(&blob_bytes).await?;
569 store
570 .update_ref_cas(&ref_name, Some(&blob_oid), expected_old_oid)
571 .await?;
572 Ok(blob_oid)
573}
574
575pub async fn load_dag_from_git<T>(
577 store: &dyn GitStore,
578 kind: &str,
579 id: &str,
580 identity: &dyn Identity,
581 expected_repo_id: Option<&RepoId>,
582) -> Result<Option<(Oid, Dag<T>)>, CobError>
583where
584 T: Serialize + for<'de> Deserialize<'de>,
585{
586 let ref_name = cob_ref_name(kind, id)?;
587 let Some(oid) = store.resolve_ref(&ref_name).await? else {
588 return Ok(None);
589 };
590 let obj = store.read_object(&oid).await?;
591 if obj.kind != GitObjectKind::Blob {
592 return Err(CobError::UnexpectedGitObjectKind);
593 }
594 let envelope: CobBlobEnvelope<T> = serde_json::from_slice(&obj.bytes)?;
595 if envelope.version != 1 {
596 return Err(CobError::InvalidOp(format!(
597 "unsupported COB snapshot version {}",
598 envelope.version
599 )));
600 }
601 let mut dag = Dag::new();
602 for op in envelope.ops {
603 dag.insert_verified(op, identity, expected_repo_id, Some(kind))
604 .await?;
605 }
606 Ok(Some((oid, dag)))
607}
608
609#[cfg(test)]
610mod tests {
611 use super::*;
612 use gitiverse_git::CliGitStore;
613 use wire_mesh_core::adapters::NodeIdentity;
614
615 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
616 struct SamplePayload(String);
617
618 #[tokio::test]
619 async fn signed_dag_op_verifies_and_persists_to_bare_git_store() {
620 let dir = tempfile::tempdir().unwrap();
621 let store = CliGitStore::init_bare_at(dir.path()).await.unwrap();
622 let alice = NodeIdentity::generate_ed25519();
623 let bob = NodeIdentity::generate_es256();
624 let repo_id = RepoId::from_bytes([0x77; 32]);
625
626 let op1 = DagOp::sign_new(
627 repo_id,
628 "sample",
629 vec![],
630 1,
631 100,
632 SamplePayload("root".to_owned()),
633 &alice,
634 )
635 .await
636 .unwrap();
637 let id1 = op1.op_id().unwrap();
638
639 let op2 = DagOp::sign_new(
640 repo_id,
641 "sample",
642 vec![id1],
643 2,
644 200,
645 SamplePayload("child".to_owned()),
646 &bob,
647 )
648 .await
649 .unwrap();
650 let id2 = op2.op_id().unwrap();
651
652 let mut dag = Dag::new();
653 dag.insert_verified(op2, &alice, Some(&repo_id), Some("sample"))
654 .await
655 .unwrap();
656 dag.insert_verified(op1, &bob, Some(&repo_id), Some("sample"))
657 .await
658 .unwrap();
659 assert_eq!(dag.tips(), vec![id2]);
660
661 let blob_oid = save_dag_to_git(&store, "sample", &id1.to_hex(), &dag, None)
662 .await
663 .unwrap();
664
665 let (loaded_oid, loaded_dag) = load_dag_from_git::<SamplePayload>(
666 &store,
667 "sample",
668 &id1.to_hex(),
669 &alice,
670 Some(&repo_id),
671 )
672 .await
673 .unwrap()
674 .unwrap();
675 assert_eq!(loaded_oid, blob_oid);
676 assert_eq!(loaded_dag, dag);
677 }
678
679 #[tokio::test]
680 async fn tampered_op_and_missing_parent_and_lamport_regression_fail() {
681 let alice = NodeIdentity::generate_ed25519();
682 let repo_id = RepoId::from_bytes([0x12; 32]);
683 let mut op = DagOp::sign_new(
684 repo_id,
685 "sample",
686 vec![],
687 1,
688 100,
689 SamplePayload("hello".to_owned()),
690 &alice,
691 )
692 .await
693 .unwrap();
694 let root_id = op.op_id().unwrap();
695 op.payload = SamplePayload("tampered".to_owned());
696 assert!(matches!(
697 op.verify(&alice, Some(&repo_id), Some("sample")).await,
698 Err(CobError::BadSignature)
699 ));
700
701 let orphan = DagOp::sign_new(
702 repo_id,
703 "sample",
704 vec![root_id],
705 2,
706 101,
707 SamplePayload("orphan".to_owned()),
708 &alice,
709 )
710 .await
711 .unwrap();
712 let mut dag = Dag::new();
713 dag.insert_unchecked(orphan).unwrap();
714 assert!(matches!(
715 dag.topological_order(),
716 Err(CobError::MissingParent { .. })
717 ));
718
719 let valid_root = DagOp::sign_new(
720 repo_id,
721 "sample",
722 vec![],
723 5,
724 100,
725 SamplePayload("root".to_owned()),
726 &alice,
727 )
728 .await
729 .unwrap();
730 let valid_root_id = valid_root.op_id().unwrap();
731 let regressed = DagOp::sign_new(
732 repo_id,
733 "sample",
734 vec![valid_root_id],
735 5,
736 101,
737 SamplePayload("bad clock".to_owned()),
738 &alice,
739 )
740 .await
741 .unwrap();
742 let mut bad_clock_dag = Dag::new();
743 bad_clock_dag.insert_unchecked(valid_root).unwrap();
744 bad_clock_dag.insert_unchecked(regressed).unwrap();
745 assert!(matches!(
746 bad_clock_dag.topological_order(),
747 Err(CobError::InvalidLamport { .. })
748 ));
749 }
750}