synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-radicle / src / lib.rs
| 1 | //! Radicle `refs/rad/id` identity document and `refs/namespaces/<nid>/refs/rad/sigrefs` |
| 2 | //! Ed25519 delegate threshold verifier, canonical promotion gate, and split-brain |
| 3 | //! reconciliation state machine (`synapse-radicle`, Gate 3). |
| 4 | |
| 5 | pub mod identity; |
| 6 | |
| 7 | pub use identity::{ |
| 8 | Ed25519PublicKey, IdentityDocumentDigest, IdentityEdit, IdentityLog, IdentityLogEntry, |
| 9 | IdentitySignature, ReceiptRefusal, RepositoryIdentityDocument, |
| 10 | }; |
| 11 | |
| 12 | use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; |
| 13 | use serde::{Deserialize, Serialize}; |
| 14 | use std::collections::BTreeMap; |
| 15 | use std::path::Path; |
| 16 | use std::process::Command; |
| 17 | use synapse_core::{ |
| 18 | decode_did_key_ed25519, encode_did_key_ed25519, ChangesetId, GitOid, RadicleCanonicalHead, |
| 19 | RefusalCode, RepoId, SynapseError, SynapseResult, |
| 20 | }; |
| 21 | |
| 22 | /// Radicle project payload inside `embeds/radicle.json` (`payload["xyz.radicle.project"]`). |
| 23 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 24 | #[serde(rename_all = "camelCase")] |
| 25 | pub struct RadicleProjectPayload { |
| 26 | pub default_branch: String, |
| 27 | #[serde(default)] |
| 28 | pub description: String, |
| 29 | pub name: String, |
| 30 | } |
| 31 | |
| 32 | /// Top-level payload map in `embeds/radicle.json`. |
| 33 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 34 | pub struct RadiclePayloadMap { |
| 35 | #[serde(rename = "xyz.radicle.project")] |
| 36 | pub project: RadicleProjectPayload, |
| 37 | } |
| 38 | |
| 39 | /// Wire format of Radicle's `refs/rad/id:embeds/radicle.json` identity document. |
| 40 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 41 | pub struct RadicleIdentityDoc { |
| 42 | pub delegates: Vec<String>, |
| 43 | pub payload: RadiclePayloadMap, |
| 44 | pub threshold: usize, |
| 45 | } |
| 46 | |
| 47 | impl RadicleIdentityDoc { |
| 48 | /// Validate delegate `did:key:z6Mk...` encodings and threshold bounds. |
| 49 | pub fn validate(&self) -> SynapseResult<()> { |
| 50 | if self.delegates.is_empty() { |
| 51 | return Err(SynapseError::new( |
| 52 | RefusalCode::RadicleIdentityInvalid, |
| 53 | "Radicle identity document must have at least one delegate", |
| 54 | )); |
| 55 | } |
| 56 | if self.threshold == 0 || self.threshold > self.delegates.len() { |
| 57 | return Err(SynapseError::new( |
| 58 | RefusalCode::RadicleIdentityInvalid, |
| 59 | format!( |
| 60 | "invalid Radicle threshold {} for {} delegates", |
| 61 | self.threshold, |
| 62 | self.delegates.len() |
| 63 | ), |
| 64 | )); |
| 65 | } |
| 66 | if self.payload.project.default_branch.trim().is_empty() { |
| 67 | return Err(SynapseError::new( |
| 68 | RefusalCode::RadicleIdentityInvalid, |
| 69 | "Radicle project defaultBranch cannot be empty", |
| 70 | )); |
| 71 | } |
| 72 | for delegate_did in &self.delegates { |
| 73 | let _ = decode_did_key_ed25519(delegate_did)?; |
| 74 | } |
| 75 | Ok(()) |
| 76 | } |
| 77 | |
| 78 | pub fn default_branch_ref(&self) -> String { |
| 79 | format!("refs/heads/{}", self.payload.project.default_branch) |
| 80 | } |
| 81 | |
| 82 | pub fn compute_doc_oid_hint(&self) -> GitOid { |
| 83 | let json = serde_json::to_vec(self).unwrap_or_default(); |
| 84 | GitOid::compute_blob(&json) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// Wire bundle for a single delegate's `refs/namespaces/<nid>/refs/rad/sigrefs`. |
| 89 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 90 | pub struct DelegateSigrefs { |
| 91 | /// Delegate node identity (`did:key:z6Mk...` or bare `z6Mk...`). |
| 92 | pub delegate_did: String, |
| 93 | /// Exact contents of the `refs` blob inside `refs/rad/sigrefs` (sorted `<oid> <refname>\n` lines). |
| 94 | pub refs_blob: Vec<u8>, |
| 95 | /// Raw 64-byte Ed25519 `signature` blob inside `refs/rad/sigrefs` over `refs_blob`. |
| 96 | pub signature_blob: Vec<u8>, |
| 97 | } |
| 98 | |
| 99 | impl DelegateSigrefs { |
| 100 | /// Helper to sign a sorted `refs` map with a delegate's Ed25519 `SigningKey`. |
| 101 | pub fn sign_refs(delegate_key: &SigningKey, refs: &BTreeMap<String, GitOid>) -> Self { |
| 102 | let delegate_did = encode_did_key_ed25519(&delegate_key.verifying_key().to_bytes()); |
| 103 | let mut refs_text = String::new(); |
| 104 | for (refname, oid) in refs { |
| 105 | refs_text.push_str(&format!("{} {}\n", oid.to_hex(), refname)); |
| 106 | } |
| 107 | let refs_blob = refs_text.into_bytes(); |
| 108 | let signature_blob = delegate_key.sign(&refs_blob).to_bytes().to_vec(); |
| 109 | Self { |
| 110 | delegate_did, |
| 111 | refs_blob, |
| 112 | signature_blob, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Cryptographically verify the delegate's Ed25519 signature over `refs_blob` |
| 117 | /// and parse the signed `refname -> GitOid` table. |
| 118 | pub fn verify_and_parse(&self) -> SynapseResult<(String, BTreeMap<String, GitOid>)> { |
| 119 | let normalized_did = if self.delegate_did.starts_with("did:key:") { |
| 120 | self.delegate_did.clone() |
| 121 | } else { |
| 122 | format!("did:key:{}", self.delegate_did) |
| 123 | }; |
| 124 | let pubkey_bytes = decode_did_key_ed25519(&normalized_did)?; |
| 125 | let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes).map_err(|_| { |
| 126 | SynapseError::new( |
| 127 | RefusalCode::RadicleIdentityInvalid, |
| 128 | "invalid delegate Ed25519 public key", |
| 129 | ) |
| 130 | })?; |
| 131 | let sig_arr: [u8; 64] = self.signature_blob.as_slice().try_into().map_err(|_| { |
| 132 | SynapseError::new( |
| 133 | RefusalCode::RadicleSignatureInvalid, |
| 134 | "Radicle sigrefs signature must be 64 bytes", |
| 135 | ) |
| 136 | })?; |
| 137 | let sig = Signature::from_bytes(&sig_arr); |
| 138 | verifying_key.verify(&self.refs_blob, &sig).map_err(|_| { |
| 139 | SynapseError::new( |
| 140 | RefusalCode::RadicleSignatureInvalid, |
| 141 | format!("Ed25519 signature verification failed for delegate {normalized_did}"), |
| 142 | ) |
| 143 | })?; |
| 144 | |
| 145 | let text = std::str::from_utf8(&self.refs_blob).map_err(|_| { |
| 146 | SynapseError::new( |
| 147 | RefusalCode::RadicleSignatureInvalid, |
| 148 | "sigrefs refs blob is not valid UTF-8", |
| 149 | ) |
| 150 | })?; |
| 151 | |
| 152 | let mut parsed = BTreeMap::new(); |
| 153 | for line in text.lines() { |
| 154 | let trimmed = line.trim(); |
| 155 | if trimmed.is_empty() { |
| 156 | continue; |
| 157 | } |
| 158 | let (oid_hex, refname) = trimmed.split_once(' ').ok_or_else(|| { |
| 159 | SynapseError::new( |
| 160 | RefusalCode::RadicleSignatureInvalid, |
| 161 | format!("malformed sigrefs line: {trimmed}"), |
| 162 | ) |
| 163 | })?; |
| 164 | let oid = GitOid::from_hex(oid_hex)?; |
| 165 | parsed.insert(refname.to_string(), oid); |
| 166 | } |
| 167 | |
| 168 | Ok((normalized_did, parsed)) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// Classification of repository canonical reconciliation state across Radicle and GitHub. |
| 173 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 174 | pub enum ReconciliationState { |
| 175 | /// Radicle delegate threshold is satisfied for `canonical_oid`. |
| 176 | CanonicalQuorumSatisfied { |
| 177 | canonical_oid: GitOid, |
| 178 | verified_delegates: Vec<String>, |
| 179 | }, |
| 180 | /// Split-brain Case 1: A GitHub PR was marked merged, but Radicle delegate threshold is absent. |
| 181 | /// Canonical promotion is refused until Radicle delegate threshold is satisfied. |
| 182 | SplitBrainGithubMergedWithoutRadicleQuorum { |
| 183 | candidate_oid: GitOid, |
| 184 | verified_count: usize, |
| 185 | required_threshold: usize, |
| 186 | }, |
| 187 | /// Split-brain Case 2: Radicle delegate quorum points to `radicle_canonical_oid`, |
| 188 | /// which diverges from the candidate `candidate_oid`. |
| 189 | SplitBrainRadicleCanonicalDiverged { |
| 190 | radicle_canonical_oid: GitOid, |
| 191 | candidate_oid: GitOid, |
| 192 | }, |
| 193 | /// Network partition Case 4: Fewer than `threshold` delegate `sigrefs` are reachable. |
| 194 | PartitionedAwaitingDelegates { |
| 195 | reachable_verified: usize, |
| 196 | required_threshold: usize, |
| 197 | }, |
| 198 | } |
| 199 | |
| 200 | /// Input bundle for evaluating canonical promotion of a candidate commit. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 202 | pub struct PromotionCandidate { |
| 203 | pub repo_id: RepoId, |
| 204 | pub changeset_id: Option<ChangesetId>, |
| 205 | pub proposal_base_git_oid: GitOid, |
| 206 | pub candidate_git_oid: GitOid, |
| 207 | pub github_pr_merged: bool, |
| 208 | pub verified_at_ms: u64, |
| 209 | } |
| 210 | |
| 211 | /// Radicle canonical promotion and split-brain reconciliation verifier. |
| 212 | pub struct CanonicalPromotionEngine { |
| 213 | identity_doc: RadicleIdentityDoc, |
| 214 | identity_doc_oid: GitOid, |
| 215 | current_canonical: Option<RadicleCanonicalHead>, |
| 216 | } |
| 217 | |
| 218 | impl CanonicalPromotionEngine { |
| 219 | pub fn new( |
| 220 | identity_doc: RadicleIdentityDoc, |
| 221 | identity_doc_oid: Option<GitOid>, |
| 222 | current_canonical: Option<RadicleCanonicalHead>, |
| 223 | ) -> SynapseResult<Self> { |
| 224 | identity_doc.validate()?; |
| 225 | let doc_oid = identity_doc_oid.unwrap_or_else(|| identity_doc.compute_doc_oid_hint()); |
| 226 | Ok(Self { |
| 227 | identity_doc, |
| 228 | identity_doc_oid: doc_oid, |
| 229 | current_canonical, |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | pub fn current_canonical(&self) -> Option<&RadicleCanonicalHead> { |
| 234 | self.current_canonical.as_ref() |
| 235 | } |
| 236 | |
| 237 | /// Inspect the reconciliation state between `candidate` and the available `delegate_sigrefs` |
| 238 | /// without mutating canonical state. |
| 239 | pub fn classify_reconciliation( |
| 240 | &self, |
| 241 | candidate: &PromotionCandidate, |
| 242 | delegate_sigrefs: &[DelegateSigrefs], |
| 243 | ) -> SynapseResult<ReconciliationState> { |
| 244 | let default_ref = self.identity_doc.default_branch_ref(); |
| 245 | let mut votes_by_oid: BTreeMap<GitOid, Vec<String>> = BTreeMap::new(); |
| 246 | let mut verified_for_candidate = Vec::new(); |
| 247 | |
| 248 | for sigref in delegate_sigrefs { |
| 249 | let (norm_did, refs_map) = sigref.verify_and_parse()?; |
| 250 | if !self.identity_doc.delegates.contains(&norm_did) { |
| 251 | return Err(SynapseError::new( |
| 252 | RefusalCode::RadicleIdentityInvalid, |
| 253 | format!("signer {norm_did} is not an authorized delegate in refs/rad/id"), |
| 254 | )); |
| 255 | } |
| 256 | if let Some(&signed_oid) = refs_map.get(&default_ref) { |
| 257 | let voters = votes_by_oid.entry(signed_oid).or_default(); |
| 258 | if !voters.contains(&norm_did) { |
| 259 | voters.push(norm_did.clone()); |
| 260 | } |
| 261 | if signed_oid == candidate.candidate_git_oid |
| 262 | && !verified_for_candidate.contains(&norm_did) |
| 263 | { |
| 264 | verified_for_candidate.push(norm_did); |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | // Check if Radicle delegate threshold already converged on a DIFFERENT commit OID |
| 270 | for (oid, voters) in &votes_by_oid { |
| 271 | if voters.len() >= self.identity_doc.threshold && *oid != candidate.candidate_git_oid { |
| 272 | return Ok(ReconciliationState::SplitBrainRadicleCanonicalDiverged { |
| 273 | radicle_canonical_oid: *oid, |
| 274 | candidate_oid: candidate.candidate_git_oid, |
| 275 | }); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | if verified_for_candidate.len() >= self.identity_doc.threshold { |
| 280 | return Ok(ReconciliationState::CanonicalQuorumSatisfied { |
| 281 | canonical_oid: candidate.candidate_git_oid, |
| 282 | verified_delegates: verified_for_candidate, |
| 283 | }); |
| 284 | } |
| 285 | |
| 286 | if candidate.github_pr_merged { |
| 287 | Ok( |
| 288 | ReconciliationState::SplitBrainGithubMergedWithoutRadicleQuorum { |
| 289 | candidate_oid: candidate.candidate_git_oid, |
| 290 | verified_count: verified_for_candidate.len(), |
| 291 | required_threshold: self.identity_doc.threshold, |
| 292 | }, |
| 293 | ) |
| 294 | } else { |
| 295 | Ok(ReconciliationState::PartitionedAwaitingDelegates { |
| 296 | reachable_verified: verified_for_candidate.len(), |
| 297 | required_threshold: self.identity_doc.threshold, |
| 298 | }) |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | /// Verify Radicle identity, signed refs, base freshness, and delegate threshold, |
| 303 | /// promoting `candidate` to `RadicleCanonicalHead` only when all invariants hold. |
| 304 | pub fn verify_and_promote( |
| 305 | &mut self, |
| 306 | candidate: &PromotionCandidate, |
| 307 | delegate_sigrefs: &[DelegateSigrefs], |
| 308 | ) -> SynapseResult<RadicleCanonicalHead> { |
| 309 | // 1. Stale-base refusal: if a canonical head is already established, the proposal's |
| 310 | // base must match the current canonical head OID. |
| 311 | if let Some(ref curr) = self.current_canonical { |
| 312 | if candidate.proposal_base_git_oid != curr.canonical_git_oid { |
| 313 | return Err(SynapseError::new( |
| 314 | RefusalCode::StaleBaseHead, |
| 315 | format!( |
| 316 | "stale proposal base {} != current Radicle canonical head {}", |
| 317 | candidate.proposal_base_git_oid, curr.canonical_git_oid |
| 318 | ), |
| 319 | )); |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // 2. Classify reconciliation state and verify all delegate Ed25519 signatures |
| 324 | match self.classify_reconciliation(candidate, delegate_sigrefs)? { |
| 325 | ReconciliationState::CanonicalQuorumSatisfied { |
| 326 | canonical_oid, |
| 327 | verified_delegates, |
| 328 | } => { |
| 329 | let head = RadicleCanonicalHead { |
| 330 | repo_id: candidate.repo_id.clone(), |
| 331 | default_branch: self.identity_doc.payload.project.default_branch.clone(), |
| 332 | canonical_git_oid: canonical_oid, |
| 333 | promoted_changeset_id: candidate.changeset_id, |
| 334 | rad_id_commit_oid: self.identity_doc_oid, |
| 335 | verified_delegates, |
| 336 | threshold: self.identity_doc.threshold, |
| 337 | verified_at_ms: candidate.verified_at_ms, |
| 338 | }; |
| 339 | self.current_canonical = Some(head.clone()); |
| 340 | Ok(head) |
| 341 | } |
| 342 | ReconciliationState::SplitBrainRadicleCanonicalDiverged { |
| 343 | radicle_canonical_oid, |
| 344 | candidate_oid, |
| 345 | } => Err(SynapseError::new( |
| 346 | RefusalCode::SplitBrainDivergence, |
| 347 | format!( |
| 348 | "Radicle canonical quorum points to {radicle_canonical_oid}, diverging from candidate {candidate_oid}" |
| 349 | ), |
| 350 | )), |
| 351 | ReconciliationState::SplitBrainGithubMergedWithoutRadicleQuorum { |
| 352 | candidate_oid, |
| 353 | verified_count, |
| 354 | required_threshold, |
| 355 | } => Err(SynapseError::new( |
| 356 | RefusalCode::RadicleQuorumInsufficient, |
| 357 | format!( |
| 358 | "GitHub PR merged for {candidate_oid}, but Radicle delegate quorum is {verified_count}/{required_threshold}; refusing canonical promotion" |
| 359 | ), |
| 360 | )), |
| 361 | ReconciliationState::PartitionedAwaitingDelegates { |
| 362 | reachable_verified, |
| 363 | required_threshold, |
| 364 | } => Err(SynapseError::new( |
| 365 | RefusalCode::RadicleQuorumInsufficient, |
| 366 | format!( |
| 367 | "Radicle delegate quorum insufficient ({reachable_verified}/{required_threshold} reachable); failing closed" |
| 368 | ), |
| 369 | )), |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | /// Load `RadicleIdentityDoc` (`refs/rad/id:embeds/radicle.json`) and all delegate |
| 375 | /// `DelegateSigrefs` (`refs/namespaces/<nid>/refs/rad/sigrefs:{refs,signature}`) |
| 376 | /// directly from a real bare Radicle Git repository on disk. |
| 377 | pub fn load_radicle_state_from_bare_repo( |
| 378 | bare_repo_dir: &Path, |
| 379 | ) -> SynapseResult<(RadicleIdentityDoc, GitOid, Vec<DelegateSigrefs>)> { |
| 380 | let id_rev_out = Command::new("git") |
| 381 | .arg("--git-dir") |
| 382 | .arg(bare_repo_dir) |
| 383 | .args(["rev-parse", "refs/rad/id"]) |
| 384 | .output() |
| 385 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 386 | if !id_rev_out.status.success() { |
| 387 | return Err(SynapseError::new( |
| 388 | RefusalCode::RadicleIdentityInvalid, |
| 389 | "refs/rad/id not found in bare Radicle repository", |
| 390 | )); |
| 391 | } |
| 392 | let id_oid = GitOid::from_hex(String::from_utf8_lossy(&id_rev_out.stdout).trim())?; |
| 393 | |
| 394 | let doc_out = Command::new("git") |
| 395 | .arg("--git-dir") |
| 396 | .arg(bare_repo_dir) |
| 397 | .args(["cat-file", "blob", "refs/rad/id:embeds/radicle.json"]) |
| 398 | .output() |
| 399 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 400 | if !doc_out.status.success() { |
| 401 | return Err(SynapseError::new( |
| 402 | RefusalCode::RadicleIdentityInvalid, |
| 403 | "refs/rad/id:embeds/radicle.json not found", |
| 404 | )); |
| 405 | } |
| 406 | let doc: RadicleIdentityDoc = serde_json::from_slice(&doc_out.stdout).map_err(|e| { |
| 407 | SynapseError::new( |
| 408 | RefusalCode::RadicleIdentityInvalid, |
| 409 | format!("parse embeds/radicle.json: {e}"), |
| 410 | ) |
| 411 | })?; |
| 412 | doc.validate()?; |
| 413 | |
| 414 | let mut sigrefs_list = Vec::new(); |
| 415 | for delegate_did in &doc.delegates { |
| 416 | let nid = delegate_did |
| 417 | .strip_prefix("did:key:") |
| 418 | .unwrap_or(delegate_did); |
| 419 | let sigref_base = format!("refs/namespaces/{nid}/refs/rad/sigrefs"); |
| 420 | |
| 421 | let refs_out = Command::new("git") |
| 422 | .arg("--git-dir") |
| 423 | .arg(bare_repo_dir) |
| 424 | .args(["cat-file", "blob", &format!("{sigref_base}:refs")]) |
| 425 | .output() |
| 426 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 427 | let sig_out = Command::new("git") |
| 428 | .arg("--git-dir") |
| 429 | .arg(bare_repo_dir) |
| 430 | .args(["cat-file", "blob", &format!("{sigref_base}:signature")]) |
| 431 | .output() |
| 432 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 433 | |
| 434 | if refs_out.status.success() && sig_out.status.success() { |
| 435 | sigrefs_list.push(DelegateSigrefs { |
| 436 | delegate_did: delegate_did.clone(), |
| 437 | refs_blob: refs_out.stdout, |
| 438 | signature_blob: sig_out.stdout, |
| 439 | }); |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | Ok((doc, id_oid, sigrefs_list)) |
| 444 | } |
| 445 | |
| 446 | #[cfg(test)] |
| 447 | mod tests { |
| 448 | use super::*; |
| 449 | |
| 450 | #[test] |
| 451 | fn test_radicle_quorum_and_all_five_split_brain_cases() { |
| 452 | let del1_key = SigningKey::from_bytes(&[51u8; 32]); |
| 453 | let del1_did = encode_did_key_ed25519(&del1_key.verifying_key().to_bytes()); |
| 454 | let del2_key = SigningKey::from_bytes(&[52u8; 32]); |
| 455 | let del2_did = encode_did_key_ed25519(&del2_key.verifying_key().to_bytes()); |
| 456 | let del3_key = SigningKey::from_bytes(&[53u8; 32]); |
| 457 | let del3_did = encode_did_key_ed25519(&del3_key.verifying_key().to_bytes()); |
| 458 | |
| 459 | let doc = RadicleIdentityDoc { |
| 460 | delegates: vec![del1_did, del2_did, del3_did], |
| 461 | payload: RadiclePayloadMap { |
| 462 | project: RadicleProjectPayload { |
| 463 | default_branch: "main".to_string(), |
| 464 | description: "Sovereign changeset engine".to_string(), |
| 465 | name: "synapse".to_string(), |
| 466 | }, |
| 467 | }, |
| 468 | threshold: 2, // 2-of-3 delegate quorum required! |
| 469 | }; |
| 470 | |
| 471 | let repo_id = RepoId::new("aien-spark/synapse").unwrap(); |
| 472 | let genesis_oid = GitOid::compute_blob(b"genesis-commit"); |
| 473 | let commit_v1 = GitOid::compute_blob(b"commit-v1"); |
| 474 | let commit_diverged = GitOid::compute_blob(b"commit-diverged"); |
| 475 | let commit_v2 = GitOid::compute_blob(b"commit-v2"); |
| 476 | |
| 477 | let mut engine = CanonicalPromotionEngine::new(doc, None, None).unwrap(); |
| 478 | |
| 479 | let cand_v1_gh_merged = PromotionCandidate { |
| 480 | repo_id: repo_id.clone(), |
| 481 | changeset_id: Some(ChangesetId([0x11; 32])), |
| 482 | proposal_base_git_oid: genesis_oid, |
| 483 | candidate_git_oid: commit_v1, |
| 484 | github_pr_merged: true, |
| 485 | verified_at_ms: 1_000, |
| 486 | }; |
| 487 | |
| 488 | // Only 1 delegate (`del1`) has signed `commit_v1` so far |
| 489 | let mut refs_v1 = BTreeMap::new(); |
| 490 | refs_v1.insert("refs/heads/main".to_string(), commit_v1); |
| 491 | let sig1_v1 = DelegateSigrefs::sign_refs(&del1_key, &refs_v1); |
| 492 | |
| 493 | // SPLIT-BRAIN CASE 1: GitHub PR is merged (`github_pr_merged: true`), |
| 494 | // while Radicle 2-of-3 threshold is absent (only 1/2 signed). |
| 495 | let state_case1 = engine |
| 496 | .classify_reconciliation(&cand_v1_gh_merged, std::slice::from_ref(&sig1_v1)) |
| 497 | .unwrap(); |
| 498 | assert_eq!( |
| 499 | state_case1, |
| 500 | ReconciliationState::SplitBrainGithubMergedWithoutRadicleQuorum { |
| 501 | candidate_oid: commit_v1, |
| 502 | verified_count: 1, |
| 503 | required_threshold: 2, |
| 504 | } |
| 505 | ); |
| 506 | let err_case1 = engine |
| 507 | .verify_and_promote(&cand_v1_gh_merged, std::slice::from_ref(&sig1_v1)) |
| 508 | .unwrap_err(); |
| 509 | assert_eq!(err_case1.code, RefusalCode::RadicleQuorumInsufficient); |
| 510 | assert!(engine.current_canonical().is_none()); |
| 511 | |
| 512 | // SPLIT-BRAIN CASE 2: Radicle 2-of-3 delegate quorum points elsewhere (`commit_diverged`) |
| 513 | let mut refs_div = BTreeMap::new(); |
| 514 | refs_div.insert("refs/heads/main".to_string(), commit_diverged); |
| 515 | let sig2_div = DelegateSigrefs::sign_refs(&del2_key, &refs_div); |
| 516 | let sig3_div = DelegateSigrefs::sign_refs(&del3_key, &refs_div); |
| 517 | |
| 518 | let err_case2 = engine |
| 519 | .verify_and_promote(&cand_v1_gh_merged, &[sig1_v1.clone(), sig2_div, sig3_div]) |
| 520 | .unwrap_err(); |
| 521 | assert_eq!(err_case2.code, RefusalCode::SplitBrainDivergence); |
| 522 | |
| 523 | // SPLIT-BRAIN CASE 4 (Network Partition): `github_pr_merged: false`, only 1/2 delegates reachable |
| 524 | let mut cand_v1_partitioned = cand_v1_gh_merged.clone(); |
| 525 | cand_v1_partitioned.github_pr_merged = false; |
| 526 | let state_case4 = engine |
| 527 | .classify_reconciliation(&cand_v1_partitioned, std::slice::from_ref(&sig1_v1)) |
| 528 | .unwrap(); |
| 529 | assert_eq!( |
| 530 | state_case4, |
| 531 | ReconciliationState::PartitionedAwaitingDelegates { |
| 532 | reachable_verified: 1, |
| 533 | required_threshold: 2, |
| 534 | } |
| 535 | ); |
| 536 | let err_case4 = engine |
| 537 | .verify_and_promote(&cand_v1_partitioned, std::slice::from_ref(&sig1_v1)) |
| 538 | .unwrap_err(); |
| 539 | assert_eq!(err_case4.code, RefusalCode::RadicleQuorumInsufficient); |
| 540 | |
| 541 | // Tampered signature refusal check |
| 542 | let mut bad_sig = sig1_v1.clone(); |
| 543 | bad_sig.signature_blob[0] ^= 0xff; |
| 544 | let bad_err = engine |
| 545 | .verify_and_promote(&cand_v1_partitioned, &[bad_sig]) |
| 546 | .unwrap_err(); |
| 547 | assert_eq!(bad_err.code, RefusalCode::RadicleSignatureInvalid); |
| 548 | |
| 549 | // SPLIT-BRAIN CASE 5 (Restored Peer): Partition heals, `del2` signs `commit_v1` -> 2-of-3 quorum satisfied! |
| 550 | let sig2_v1 = DelegateSigrefs::sign_refs(&del2_key, &refs_v1); |
| 551 | let promoted_v1 = engine |
| 552 | .verify_and_promote(&cand_v1_partitioned, &[sig1_v1, sig2_v1]) |
| 553 | .unwrap(); |
| 554 | assert_eq!(promoted_v1.canonical_git_oid, commit_v1); |
| 555 | assert_eq!(promoted_v1.verified_delegates.len(), 2); |
| 556 | |
| 557 | // SPLIT-BRAIN CASE 3 (Stale Agent Proposal): Now that canonical head is `commit_v1`, |
| 558 | // an agent proposal still based on `genesis_oid` is refused with `StaleBaseHead`! |
| 559 | let mut refs_v2 = BTreeMap::new(); |
| 560 | refs_v2.insert("refs/heads/main".to_string(), commit_v2); |
| 561 | let sig1_v2 = DelegateSigrefs::sign_refs(&del1_key, &refs_v2); |
| 562 | let sig2_v2 = DelegateSigrefs::sign_refs(&del2_key, &refs_v2); |
| 563 | |
| 564 | let stale_cand = PromotionCandidate { |
| 565 | repo_id, |
| 566 | changeset_id: Some(ChangesetId([0x22; 32])), |
| 567 | proposal_base_git_oid: genesis_oid, // Stale! Current canonical is `commit_v1` |
| 568 | candidate_git_oid: commit_v2, |
| 569 | github_pr_merged: false, |
| 570 | verified_at_ms: 2_000, |
| 571 | }; |
| 572 | let stale_err = engine |
| 573 | .verify_and_promote(&stale_cand, &[sig1_v2, sig2_v2]) |
| 574 | .unwrap_err(); |
| 575 | assert_eq!(stale_err.code, RefusalCode::StaleBaseHead); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn test_real_host_radicle_storage_sigrefs_verification() { |
| 580 | // If `$HOME/.radicle/storage/z21SQF1DVwRmpxbTMnSiYxXveiRp1` exists on this host, |
| 581 | // verify our parser and Ed25519 `sigrefs` verifier against the live Radicle storage! |
| 582 | let Some(home) = std::env::var_os("HOME") else { |
| 583 | return; |
| 584 | }; |
| 585 | let real_repo = Path::new(&home).join(".radicle/storage/z21SQF1DVwRmpxbTMnSiYxXveiRp1"); |
| 586 | if !real_repo.exists() { |
| 587 | return; |
| 588 | } |
| 589 | let (doc, id_oid, sigrefs) = load_radicle_state_from_bare_repo(&real_repo).unwrap(); |
| 590 | assert_eq!(doc.threshold, 1); |
| 591 | assert_eq!(doc.delegates.len(), 1); |
| 592 | assert_eq!(sigrefs.len(), 1); |
| 593 | |
| 594 | let (verified_did, parsed_refs) = sigrefs[0].verify_and_parse().unwrap(); |
| 595 | assert_eq!(verified_did, doc.delegates[0]); |
| 596 | let main_oid = *parsed_refs.get("refs/heads/main").unwrap(); |
| 597 | |
| 598 | let mut engine = CanonicalPromotionEngine::new(doc, Some(id_oid), None).unwrap(); |
| 599 | let cand = PromotionCandidate { |
| 600 | repo_id: RepoId::new("aien-spark/aien-sovereign-core").unwrap(), |
| 601 | changeset_id: None, |
| 602 | proposal_base_git_oid: GitOid::ZERO, |
| 603 | candidate_git_oid: main_oid, |
| 604 | github_pr_merged: false, |
| 605 | verified_at_ms: 1_700_000_000_000, |
| 606 | }; |
| 607 | let head = engine.verify_and_promote(&cand, &sigrefs).unwrap(); |
| 608 | assert_eq!(head.canonical_git_oid, main_oid); |
| 609 | assert_eq!(head.rad_id_commit_oid, id_oid); |
| 610 | } |
| 611 | } |