Something went wrong. Try again.
A public mirror for the whole atmosphere hubble.microcosm.blue
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243//! The signed repo commit at `C<pds>\0<did>` in the `default` CF.//!//! Written once per successful fetch from `getRepo` (in the same final//! batch as the new `R<pds>\0<did>` and `s<pds>\0<did>` rows). The//! parsed fields cover everything an offline authenticity check needs —//! `did`, `version`, `data`, `rev`, `prev`, `sig` — with the spec's//! canonical-DAG-CBOR contract (§2.7) doing the byte-fidelity work//! implicitly: a verifier re-canonicalizes commit-minus-sig from these//! fields, hashes, and checks the signature against the recovered key.//! If a PDS published non-canonical signed bytes, signature//! verification *should* fail — that's the spec working as designed.
use hubble_pds::Hostname;use rocksdb::WriteBatch;use serde::{Deserialize, Serialize};
use super::{Db, DbError, PREFIX_COMMIT, Result, SEP, assert_no_nul};
// ---------------------------------------------------------------------------// Key encoding// ---------------------------------------------------------------------------
pub fn key(pds: &Hostname, did: &str) -> Vec<u8> { assert_no_nul(did); let pds = pds.as_ref(); let mut k = Vec::with_capacity(1 + pds.len() + 1 + did.len()); k.push(PREFIX_COMMIT); k.extend_from_slice(pds.as_bytes()); k.push(SEP); k.extend_from_slice(did.as_bytes()); k}
// ---------------------------------------------------------------------------// Type// ---------------------------------------------------------------------------
/// All six signed-commit fields preserved from the last successful/// fetch. `data` and `prev` are stored as base32-multibase CID/// strings; `sig` is the raw signature bytes.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct StoredCommit { pub did: String, pub version: u64, /// MST root CID, base32-multibase. pub data: String, /// TID-shaped revision; same lex-monotonic semantics as /// `RepoState.last_seen_rev`. pub rev: String, /// Previous commit CID, base32-multibase. Spec §2.4: required field /// on wire, typically null in v3. #[serde(default, skip_serializing_if = "Option::is_none")] pub prev: Option<String>, /// Raw signature bytes, as captured from the wire commit block. pub sig: Vec<u8>,}
// ---------------------------------------------------------------------------// Encode / decode// ---------------------------------------------------------------------------
fn encode(c: &StoredCommit) -> Result<Vec<u8>> { serde_ipld_dagcbor::to_vec(c).map_err(|e| DbError::CborEncode(e.to_string()))}
fn decode(pds: &Hostname, did: &str, bytes: &[u8]) -> Result<StoredCommit> { serde_ipld_dagcbor::from_slice(bytes).map_err(|e| DbError::CborDecode { key: format!("C{}\\0{}", pds.as_ref(), did), reason: e.to_string(), })}
// ---------------------------------------------------------------------------// Public API// ---------------------------------------------------------------------------
pub fn get(db: &Db, pds: &Hostname, did: &str) -> Result<Option<StoredCommit>> { let cf = db.cf_default()?; match db.inner.get_cf(cf, key(pds, did))? { None => Ok(None), Some(bytes) => Ok(Some(decode(pds, did, &bytes)?)), }}
/// Stage a write into `batch`.pub fn put_into( batch: &mut WriteBatch, db: &Db, pds: &Hostname, did: &str, commit: &StoredCommit,) -> Result<()> { let cf = db.cf_default()?; batch.put_cf(cf, key(pds, did), encode(commit)?); Ok(())}
/// Every `(pds, did)` pair that currently has a stored commit. A row in/// the `C/` prefix means the repo's CAR was successfully fetched and/// saved — repos that only appear in `R/` (listRepos-seen but never/// captured: inactive, tombstoned, or fetch-failed) are excluded by/// construction.////// Full `C/` prefix scan; values are skipped, only keys are decoded./// Mirrors the scan pattern in [`super::repo_state::dids_for_pds`].pub fn all_pairs(db: &Db) -> Result<Vec<(String, String)>> { let cf = db.cf_default()?; let mut read_opts = rocksdb::ReadOptions::default(); read_opts.set_iterate_lower_bound([PREFIX_COMMIT]); read_opts.set_iterate_upper_bound([PREFIX_COMMIT + 1]); let iter = db .inner .iterator_cf_opt(cf, read_opts, rocksdb::IteratorMode::Start);
let mut out = Vec::new(); for item in iter { let (k, _v) = item?; // Key: C<pds>\0<did>. Strip the C prefix, split on the first \0. let suffix = &k[1..]; let sep_idx = suffix .iter() .position(|&b| b == SEP) .ok_or_else(|| DbError::CborDecode { key: format!("C{}", String::from_utf8_lossy(suffix)), reason: "missing NUL separator in commit key".into(), })?; let pds = std::str::from_utf8(&suffix[..sep_idx]) .map_err(|e| DbError::CborDecode { key: "C<bad-utf8-pds>".into(), reason: format!("pds not utf-8: {e}"), })? .to_string(); let did = std::str::from_utf8(&suffix[sep_idx + 1..]) .map_err(|e| DbError::CborDecode { key: format!("C{}\\0<bad-utf8-did>", pds), reason: format!("did not utf-8: {e}"), })? .to_string(); out.push((pds, did)); } Ok(out)}
// ---------------------------------------------------------------------------// Tests// ---------------------------------------------------------------------------
#[cfg(test)]mod tests { use super::*; use crate::storage::open_temporary;
fn h(s: &str) -> Hostname { Hostname::new(s).unwrap() }
fn sample() -> StoredCommit { StoredCommit { did: "did:plc:abc".into(), version: 3, data: "bafyreidkjxqphmt3yhvdgmwx5p64q7s7tcmw3rj7ynvtu7tnp7nb6yurxe".into(), rev: "3kabc123".into(), prev: None, sig: vec![0xde, 0xad, 0xbe, 0xef, 0x00, 0x01, 0x02, 0x03], } }
#[test] fn key_uses_c_prefix() { let k = key(&h("example.com"), "did:plc:abc"); assert_eq!(k[0], b'C'); assert_eq!(&k[1..12], b"example.com"); assert_eq!(k[12], 0); assert_eq!(&k[13..], b"did:plc:abc"); }
#[test] fn roundtrip_via_batch() { let (db, _g) = open_temporary(); let pds = h("example.com"); let did = "did:plc:abc"; let c = sample(); let mut batch = WriteBatch::default(); put_into(&mut batch, &db, &pds, did, &c).unwrap(); db.inner.write(batch).unwrap(); let got = get(&db, &pds, did).unwrap().unwrap(); assert_eq!(got, c); }
#[test] fn missing_is_none() { let (db, _g) = open_temporary(); assert!( get(&db, &h("example.com"), "did:plc:nope") .unwrap() .is_none() ); }
#[test] fn all_pairs_scans_every_host_and_did() { let (db, _g) = open_temporary(); let a = h("a.example"); let b = h("b.example"); let mut batch = WriteBatch::default(); put_into(&mut batch, &db, &a, "did:plc:1", &sample()).unwrap(); put_into(&mut batch, &db, &a, "did:plc:2", &sample()).unwrap(); put_into(&mut batch, &db, &b, "did:plc:1", &sample()).unwrap(); db.inner.write(batch).unwrap();
let mut got = all_pairs(&db).unwrap(); got.sort(); assert_eq!( got, vec![ ("a.example".to_string(), "did:plc:1".to_string()), ("a.example".to_string(), "did:plc:2".to_string()), ("b.example".to_string(), "did:plc:1".to_string()), ] ); }
#[test] fn all_pairs_empty_db_yields_empty() { let (db, _g) = open_temporary(); assert!(all_pairs(&db).unwrap().is_empty()); }
#[test] fn prev_round_trips_when_present() { let (db, _g) = open_temporary(); let pds = h("example.com"); let did = "did:plc:abc"; let mut c = sample(); c.prev = Some("bafyreichainparentexamplecidstringalpha2345678901234567".into()); let mut batch = WriteBatch::default(); put_into(&mut batch, &db, &pds, did, &c).unwrap(); db.inner.write(batch).unwrap(); let got = get(&db, &pds, did).unwrap().unwrap(); assert_eq!(got.prev, c.prev); }}