use core::fmt;
use core::str::FromStr;
use std::collections::{BTreeMap, BTreeSet};
use gitiverse_core::ids::{ActorId, RepoId, serde_hex_bytes, serde_identity_key};
use gitiverse_git::canonical::canonical_json_bytes;
use gitiverse_git::{GitError, GitObjectKind, GitStore, Oid, validate_ref_name};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use thiserror::Error;
use wire_mesh_core::ports::{CoreError, Identity};
use wire_mesh_wire::DecodeError;
use wire_mesh_wire::identity::IdentityKey;
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::strict;
use wire_mesh_wire::value::CdeMapBuilder;
const OP_ID_BYTE_LEN: usize = 32;
const OP_ID_HEX_LEN: usize = OP_ID_BYTE_LEN * 2;
#[derive(Debug, Error)]
pub enum CobError {
#[error("invalid operation id {0:?}")]
InvalidOpId(String),
#[error("canonical serialisation error: {0}")]
Canonical(#[from] gitiverse_git::canonical::CanonicalError),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("Git store error: {0}")]
Git(#[from] GitError),
#[error("cryptographic port error: {0}")]
Crypto(#[from] CoreError),
#[error("author key does not match claimed author actor id")]
AuthorKeyMismatch,
#[error("operation signature does not verify")]
BadSignature,
#[error("operation belongs to repo {found}, expected {expected}")]
RepoMismatch { expected: RepoId, found: RepoId },
#[error("operation has kind {found:?}, expected {expected:?}")]
KindMismatch { expected: String, found: String },
#[error("invalid operation: {0}")]
InvalidOp(String),
#[error("missing causal parent {parent} referenced by operation {op_id}")]
MissingParent { op_id: OpId, parent: OpId },
#[error(
"invalid lamport clock on operation {op_id}: {lamport} must exceed parent lamport {parent_lamport}"
)]
InvalidLamport {
op_id: OpId,
lamport: u64,
parent_lamport: u64,
},
#[error("cycle detected in operation DAG")]
CycleDetected,
#[error("actor {actor} is not authorised for operation {op_id}: {reason}")]
Unauthorised {
actor: ActorId,
op_id: OpId,
reason: String,
},
#[error("corrupted COB snapshot blob: expected blob object")]
UnexpectedGitObjectKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OpId(pub [u8; OP_ID_BYTE_LEN]);
impl OpId {
#[must_use]
pub const fn from_bytes(bytes: [u8; OP_ID_BYTE_LEN]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; OP_ID_BYTE_LEN] {
&self.0
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn from_hex(s: &str) -> Result<Self, CobError> {
if s.len() != OP_ID_HEX_LEN
|| !s
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(CobError::InvalidOpId(s.to_owned()));
}
let bytes = hex::decode(s).map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
let arr: [u8; OP_ID_BYTE_LEN] = bytes
.try_into()
.map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
Ok(Self(arr))
}
}
impl fmt::Display for OpId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl FromStr for OpId {
type Err = CobError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_hex(s)
}
}
impl Serialize for OpId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for OpId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl Encode<()> for OpId {
fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
&self,
e: &mut Encoder<W>,
_ctx: &mut (),
) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
e.bytes(&self.0)?.ok()
}
}
impl Decode<'_, ()> for OpId {
fn decode(
d: &mut Decoder<'_>,
_ctx: &mut (),
) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
let bytes =
strict::bytes_value(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)?;
let arr: [u8; OP_ID_BYTE_LEN] = bytes.try_into().map_err(|v: Vec<u8>| {
wire_mesh_wire::minicbor::decode::Error::custom(DecodeError::InvalidLength {
field: "op-id",
expected: OP_ID_BYTE_LEN,
found: v.len(),
})
})?;
Ok(Self(arr))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DagOp<T> {
pub repo_id: RepoId,
pub kind: String,
pub author: ActorId,
#[serde(with = "serde_identity_key")]
pub author_key: IdentityKey,
pub parents: Vec<OpId>,
pub lamport: u64,
pub timestamp: u64,
pub payload: T,
#[serde(with = "serde_hex_bytes")]
pub signature: Vec<u8>,
}
impl<T: Serialize> DagOp<T> {
pub async fn sign_new(
repo_id: RepoId,
kind: impl Into<String>,
mut parents: Vec<OpId>,
lamport: u64,
timestamp: u64,
payload: T,
identity: &dyn Identity,
) -> Result<Self, CobError> {
let kind = kind.into();
if kind.is_empty() {
return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
}
if lamport == 0 {
return Err(CobError::InvalidOp(
"lamport clock must be at least 1".to_owned(),
));
}
parents.sort();
parents.dedup();
let mut op = Self {
repo_id,
kind,
author: ActorId(*identity.device_id()),
author_key: identity.identity_key().clone(),
parents,
lamport,
timestamp,
payload,
signature: Vec::new(),
};
let signing = op.signing_bytes()?;
op.signature = identity.sign(&signing).await?;
Ok(op)
}
pub fn signing_bytes(&self) -> Result<Vec<u8>, CobError> {
let payload_json = canonical_json_bytes(&self.payload)?;
let mut parents_buf = Vec::new();
{
let mut pe = Encoder::new(&mut parents_buf);
let _ = pe.array(self.parents.len() as u64);
for parent in &self.parents {
let _ = parent.encode(&mut pe, &mut ());
}
}
let mut builder = CdeMapBuilder::new();
builder.push("domain", "gitiverse.cob.op-sign.v1");
builder.push("repo-id", &self.repo_id);
builder.push("kind", &self.kind.as_str());
builder.push("author", &self.author);
builder.push("author-key", &self.author_key);
builder.push_raw(encoded_key("parents"), parents_buf);
builder.push("lamport", &self.lamport);
builder.push("timestamp", &self.timestamp);
builder.push_bytes("payload", &payload_json);
let mut buf = Vec::new();
let mut enc = Encoder::new(&mut buf);
let _ = builder.write(&mut enc);
Ok(buf)
}
pub fn op_id(&self) -> Result<OpId, CobError> {
let signing = self.signing_bytes()?;
let mut builder = CdeMapBuilder::new();
builder.push("domain", "gitiverse.cob.op-id.v1");
builder.push_bytes("signing", &signing);
builder.push_bytes("signature", &self.signature);
let mut buf = Vec::new();
let mut enc = Encoder::new(&mut buf);
let _ = builder.write(&mut enc);
let digest = Sha256::digest(&buf);
Ok(OpId(digest.into()))
}
pub async fn verify(
&self,
identity: &dyn Identity,
expected_repo_id: Option<&RepoId>,
expected_kind: Option<&str>,
) -> Result<OpId, CobError> {
if let Some(expected) = expected_repo_id
&& &self.repo_id != expected
{
return Err(CobError::RepoMismatch {
expected: *expected,
found: self.repo_id,
});
}
if let Some(expected) = expected_kind
&& self.kind != expected
{
return Err(CobError::KindMismatch {
expected: expected.to_owned(),
found: self.kind.clone(),
});
}
self.validate_structure()?;
if ActorId(identity.derive_device_id(&self.author_key.public_key)) != self.author {
return Err(CobError::AuthorKeyMismatch);
}
let signing = self.signing_bytes()?;
let ok = identity
.verify(&self.author_key, &signing, &self.signature)
.await?;
if !ok {
return Err(CobError::BadSignature);
}
self.op_id()
}
pub(crate) fn validate_structure(&self) -> Result<(), CobError> {
if self.kind.is_empty() {
return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
}
if self.lamport == 0 {
return Err(CobError::InvalidOp(
"lamport clock must be at least 1".to_owned(),
));
}
if !self.parents.windows(2).all(|pair| pair[0] < pair[1]) {
return Err(CobError::InvalidOp(
"operation parents must be strictly ascending and unique".to_owned(),
));
}
Ok(())
}
}
fn encoded_key(key: &str) -> Vec<u8> {
let mut buf = Vec::new();
let _ = Encoder::new(&mut buf).str(key);
buf
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dag<T> {
ops: BTreeMap<OpId, DagOp<T>>,
}
impl<T> Default for Dag<T> {
fn default() -> Self {
Self {
ops: BTreeMap::new(),
}
}
}
impl<T: Serialize> Dag<T> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn len(&self) -> usize {
self.ops.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.ops.is_empty()
}
#[must_use]
pub fn get(&self, id: &OpId) -> Option<&DagOp<T>> {
self.ops.get(id)
}
#[must_use]
pub fn contains(&self, id: &OpId) -> bool {
self.ops.contains_key(id)
}
#[must_use]
pub fn ops(&self) -> &BTreeMap<OpId, DagOp<T>> {
&self.ops
}
#[must_use]
pub fn next_lamport(&self, parents: &[OpId]) -> u64 {
parents
.iter()
.filter_map(|p| self.ops.get(p).map(|op| op.lamport))
.max()
.unwrap_or(0)
+ 1
}
pub async fn insert_verified(
&mut self,
op: DagOp<T>,
identity: &dyn Identity,
expected_repo_id: Option<&RepoId>,
expected_kind: Option<&str>,
) -> Result<OpId, CobError> {
let id = op.verify(identity, expected_repo_id, expected_kind).await?;
self.ops.entry(id).or_insert(op);
Ok(id)
}
pub fn insert_unchecked(&mut self, op: DagOp<T>) -> Result<OpId, CobError> {
op.validate_structure()?;
let id = op.op_id()?;
self.ops.entry(id).or_insert(op);
Ok(id)
}
#[must_use]
pub fn tips(&self) -> Vec<OpId> {
let mut referenced = BTreeSet::new();
for op in self.ops.values() {
for parent in &op.parents {
referenced.insert(*parent);
}
}
self.ops
.keys()
.copied()
.filter(|id| !referenced.contains(id))
.collect()
}
pub fn topological_order(&self) -> Result<Vec<(OpId, &DagOp<T>)>, CobError> {
let mut in_degree: BTreeMap<OpId, usize> = BTreeMap::new();
let mut children: BTreeMap<OpId, Vec<OpId>> = BTreeMap::new();
for (id, op) in &self.ops {
op.validate_structure()?;
for parent_id in &op.parents {
let Some(parent_op) = self.ops.get(parent_id) else {
return Err(CobError::MissingParent {
op_id: *id,
parent: *parent_id,
});
};
if op.lamport <= parent_op.lamport {
return Err(CobError::InvalidLamport {
op_id: *id,
lamport: op.lamport,
parent_lamport: parent_op.lamport,
});
}
children.entry(*parent_id).or_default().push(*id);
}
in_degree.insert(*id, op.parents.len());
}
let mut ready: BTreeSet<(u64, OpId)> = BTreeSet::new();
for (id, deg) in &in_degree {
if *deg == 0
&& let Some(op) = self.ops.get(id)
{
ready.insert((op.lamport, *id));
}
}
let mut ordered = Vec::with_capacity(self.ops.len());
while let Some((_, id)) = ready.pop_first() {
let Some(op) = self.ops.get(&id) else {
continue;
};
ordered.push((id, op));
if let Some(kids) = children.get(&id) {
for kid_id in kids {
if let Some(deg) = in_degree.get_mut(kid_id) {
*deg -= 1;
if *deg == 0
&& let Some(kid_op) = self.ops.get(kid_id)
{
ready.insert((kid_op.lamport, *kid_id));
}
}
}
}
}
if ordered.len() != self.ops.len() {
return Err(CobError::CycleDetected);
}
Ok(ordered)
}
pub fn fold<S, F>(&self, mut state: S, mut step: F) -> Result<S, CobError>
where
F: FnMut(&mut S, OpId, &DagOp<T>, &BTreeSet<OpId>) -> Result<(), CobError>,
{
let ordered = self.topological_order()?;
let mut ancestors: BTreeMap<OpId, BTreeSet<OpId>> = BTreeMap::new();
for (id, op) in ordered {
let mut op_ancestors = BTreeSet::new();
for parent_id in &op.parents {
op_ancestors.insert(*parent_id);
if let Some(parent_ancestors) = ancestors.get(parent_id) {
op_ancestors.extend(parent_ancestors.iter().copied());
}
}
step(&mut state, id, op, &op_ancestors)?;
ancestors.insert(id, op_ancestors);
}
Ok(state)
}
}
#[derive(Debug, Clone)]
pub(crate) struct Lww<T> {
pub(crate) clock: (u64, OpId),
pub(crate) value: T,
}
impl<T> Lww<T> {
pub(crate) fn new(lamport: u64, op_id: OpId, value: T) -> Self {
Self {
clock: (lamport, op_id),
value,
}
}
pub(crate) fn update(&mut self, lamport: u64, op_id: OpId, value: T) {
let candidate = (lamport, op_id);
if candidate > self.clock {
self.clock = candidate;
self.value = value;
}
}
}
pub(crate) fn require_root<'a, T>(
state: &'a mut Option<T>,
kind: &str,
op_id: OpId,
) -> Result<&'a mut T, CobError> {
state.as_mut().ok_or_else(|| {
CobError::InvalidOp(format!("{kind} operation {op_id} arrived before root op"))
})
}
pub fn cob_ref_name(kind: &str, id: &str) -> Result<String, CobError> {
if kind.is_empty()
|| id.is_empty()
|| kind.contains('/')
|| id.contains('/')
|| kind.contains("..")
|| id.contains("..")
{
return Err(CobError::InvalidOp(format!(
"invalid COB ref components kind={kind:?}, id={id:?}"
)));
}
let ref_name = format!("refs/cobs/{kind}/{id}");
validate_ref_name(&ref_name)?;
Ok(ref_name)
}
#[derive(Debug, Serialize)]
struct CobBlobWriteEnvelope<'a, T> {
version: u32,
ops: Vec<&'a DagOp<T>>,
}
#[derive(Debug, Deserialize)]
struct CobBlobEnvelope<T> {
version: u32,
ops: Vec<DagOp<T>>,
}
pub async fn save_dag_to_git<T: Serialize>(
store: &dyn GitStore,
kind: &str,
id: &str,
dag: &Dag<T>,
expected_old_oid: Option<&Oid>,
) -> Result<Oid, CobError> {
let ref_name = cob_ref_name(kind, id)?;
let ops: Vec<&DagOp<T>> = dag.ops().values().collect();
let envelope = CobBlobWriteEnvelope { version: 1, ops };
let blob_bytes = canonical_json_bytes(&envelope)?;
let blob_oid = store.write_blob(&blob_bytes).await?;
store
.update_ref_cas(&ref_name, Some(&blob_oid), expected_old_oid)
.await?;
Ok(blob_oid)
}
pub async fn load_dag_from_git<T>(
store: &dyn GitStore,
kind: &str,
id: &str,
identity: &dyn Identity,
expected_repo_id: Option<&RepoId>,
) -> Result<Option<(Oid, Dag<T>)>, CobError>
where
T: Serialize + for<'de> Deserialize<'de>,
{
let ref_name = cob_ref_name(kind, id)?;
let Some(oid) = store.resolve_ref(&ref_name).await? else {
return Ok(None);
};
let obj = store.read_object(&oid).await?;
if obj.kind != GitObjectKind::Blob {
return Err(CobError::UnexpectedGitObjectKind);
}
let envelope: CobBlobEnvelope<T> = serde_json::from_slice(&obj.bytes)?;
if envelope.version != 1 {
return Err(CobError::InvalidOp(format!(
"unsupported COB snapshot version {}",
envelope.version
)));
}
let mut dag = Dag::new();
for op in envelope.ops {
dag.insert_verified(op, identity, expected_repo_id, Some(kind))
.await?;
}
Ok(Some((oid, dag)))
}
#[cfg(test)]
mod tests {
use super::*;
use gitiverse_git::CliGitStore;
use wire_mesh_core::adapters::NodeIdentity;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct SamplePayload(String);
#[tokio::test]
async fn signed_dag_op_verifies_and_persists_to_bare_git_store() {
let dir = tempfile::tempdir().unwrap();
let store = CliGitStore::init_bare_at(dir.path()).await.unwrap();
let alice = NodeIdentity::generate_ed25519();
let bob = NodeIdentity::generate_es256();
let repo_id = RepoId::from_bytes([0x77; 32]);
let op1 = DagOp::sign_new(
repo_id,
"sample",
vec![],
1,
100,
SamplePayload("root".to_owned()),
&alice,
)
.await
.unwrap();
let id1 = op1.op_id().unwrap();
let op2 = DagOp::sign_new(
repo_id,
"sample",
vec![id1],
2,
200,
SamplePayload("child".to_owned()),
&bob,
)
.await
.unwrap();
let id2 = op2.op_id().unwrap();
let mut dag = Dag::new();
dag.insert_verified(op2, &alice, Some(&repo_id), Some("sample"))
.await
.unwrap();
dag.insert_verified(op1, &bob, Some(&repo_id), Some("sample"))
.await
.unwrap();
assert_eq!(dag.tips(), vec![id2]);
let blob_oid = save_dag_to_git(&store, "sample", &id1.to_hex(), &dag, None)
.await
.unwrap();
let (loaded_oid, loaded_dag) = load_dag_from_git::<SamplePayload>(
&store,
"sample",
&id1.to_hex(),
&alice,
Some(&repo_id),
)
.await
.unwrap()
.unwrap();
assert_eq!(loaded_oid, blob_oid);
assert_eq!(loaded_dag, dag);
}
#[tokio::test]
async fn tampered_op_and_missing_parent_and_lamport_regression_fail() {
let alice = NodeIdentity::generate_ed25519();
let repo_id = RepoId::from_bytes([0x12; 32]);
let mut op = DagOp::sign_new(
repo_id,
"sample",
vec![],
1,
100,
SamplePayload("hello".to_owned()),
&alice,
)
.await
.unwrap();
let root_id = op.op_id().unwrap();
op.payload = SamplePayload("tampered".to_owned());
assert!(matches!(
op.verify(&alice, Some(&repo_id), Some("sample")).await,
Err(CobError::BadSignature)
));
let orphan = DagOp::sign_new(
repo_id,
"sample",
vec![root_id],
2,
101,
SamplePayload("orphan".to_owned()),
&alice,
)
.await
.unwrap();
let mut dag = Dag::new();
dag.insert_unchecked(orphan).unwrap();
assert!(matches!(
dag.topological_order(),
Err(CobError::MissingParent { .. })
));
let valid_root = DagOp::sign_new(
repo_id,
"sample",
vec![],
5,
100,
SamplePayload("root".to_owned()),
&alice,
)
.await
.unwrap();
let valid_root_id = valid_root.op_id().unwrap();
let regressed = DagOp::sign_new(
repo_id,
"sample",
vec![valid_root_id],
5,
101,
SamplePayload("bad clock".to_owned()),
&alice,
)
.await
.unwrap();
let mut bad_clock_dag = Dag::new();
bad_clock_dag.insert_unchecked(valid_root).unwrap();
bad_clock_dag.insert_unchecked(regressed).unwrap();
assert!(matches!(
bad_clock_dag.topological_order(),
Err(CobError::InvalidLamport { .. })
));
}
}