//! The journal of the legal practice: every change to its lawyers, clients, //! contracts, contract versions and paper copies, in order, as a ledger. //! Each entry names the SHA-256 of the entry before it and has its own, over //! its place in the chain, its time, who made it, what it is about and the //! hash before: an entry changed or taken out later no longer matches, and //! `verify` says where. The database refuses to change or delete entries //! (migration 0009); the chain also shows a change made around that, by //! someone with the database's own rights. //! //! A version's entry names the fingerprints (SHA-256) of its text and file, //! so a version changed in the database, even with a new fingerprint, no //! longer matches its journal entry either. use anyhow::Result; use chrono::{DateTime, SecondsFormat, Timelike, Utc}; use serde::Serialize; use sqlx::{PgConnection, PgPool}; use crate::files; /// The hash before the first entry. pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000"; /// The advisory lock that orders appends, so two never take the same place. const LOCK: i64 = 0x6c64_6a72_6e6c; // "ldjrnl" /// What happened, to be written. #[derive(Debug)] pub struct New<'a> { pub actor: &'a str, pub client: Option, pub contract: Option, /// "contract added", "version added", "paper moved" ... pub event: &'a str, pub detail: String, } #[derive(Clone, Debug, sqlx::FromRow, Serialize)] pub struct Entry { pub seq: i64, pub at: DateTime, pub actor: String, pub client_id: Option, pub contract_id: Option, pub event: String, pub detail: String, pub prev_hash: String, pub hash: String, } /// Each part with its length before it, so no two entries read the same. fn part(out: &mut String, s: &str) { out.push_str(&s.len().to_string()); out.push(':'); out.push_str(s); out.push('\n'); } fn opt(id: Option) -> String { id.map(|i| i.to_string()).unwrap_or_default() } /// The entry's hash, from everything it says and the hash before it. #[allow(clippy::too_many_arguments)] pub fn hash_of( seq: i64, at: DateTime, actor: &str, client: Option, contract: Option, event: &str, detail: &str, prev: &str, ) -> String { let mut s = String::from("lanna desk journal v1\n"); part(&mut s, &seq.to_string()); part(&mut s, &at.to_rfc3339_opts(SecondsFormat::Micros, true)); part(&mut s, actor); part(&mut s, &opt(client)); part(&mut s, &opt(contract)); part(&mut s, event); part(&mut s, detail); part(&mut s, prev); files::sha256_hex(s.as_bytes()) } impl Entry { pub fn computed(&self) -> String { hash_of( self.seq, self.at, &self.actor, self.client_id, self.contract_id, &self.event, &self.detail, &self.prev_hash, ) } } /// The time to the microsecond, as the database keeps it. fn now() -> DateTime { let t = Utc::now(); t.with_nanosecond(t.nanosecond() / 1000 * 1000).unwrap_or(t) } /// Appends an entry; call it in the transaction of the change it records, /// so both commit or neither. pub async fn append(conn: &mut PgConnection, e: &New<'_>) -> Result { sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(LOCK) .execute(&mut *conn) .await?; let last: Option<(i64, String)> = sqlx::query_as("SELECT seq, hash FROM journal ORDER BY seq DESC LIMIT 1") .fetch_optional(&mut *conn) .await?; let (seq, prev) = match last { Some((s, h)) => (s + 1, h), None => (1, GENESIS.to_string()), }; let at = now(); let hash = hash_of( seq, at, e.actor, e.client, e.contract, e.event, &e.detail, &prev, ); Ok(sqlx::query_as( "INSERT INTO journal (seq, at, actor, client_id, contract_id, event, detail, prev_hash, hash) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *", ) .bind(seq) .bind(at) .bind(e.actor) .bind(e.client) .bind(e.contract) .bind(e.event) .bind(&e.detail) .bind(&prev) .bind(&hash) .fetch_one(conn) .await?) } /// The newest entries first, of one client or one contract or all. pub async fn list( db: &PgPool, client: Option, contract: Option, limit: i64, ) -> Result> { Ok(sqlx::query_as( "SELECT * FROM journal WHERE ($1::bigint IS NULL OR client_id = $1) \ AND ($2::bigint IS NULL OR contract_id = $2) ORDER BY seq DESC LIMIT $3", ) .bind(client) .bind(contract) .bind(limit) .fetch_all(db) .await?) } /// Every entry, oldest first: the CSV export. pub async fn all(db: &PgPool) -> Result> { Ok(sqlx::query_as("SELECT * FROM journal ORDER BY seq") .fetch_all(db) .await?) } /// What `verify` found. #[derive(Clone, Debug, Serialize)] pub struct Check { pub entries: i64, /// The last entry's hash: written down or exported, it pins the whole /// journal up to then. pub head: String, pub head_at: Option>, /// The problems, the first of the chain first; empty when all is whole. pub problems: Vec, } impl Check { pub fn whole(&self) -> bool { self.problems.is_empty() } } /// Checks the chain from the first entry, and every contract version's /// text and fingerprints against its entry. pub async fn verify(db: &PgPool) -> Result { let entries = all(db).await?; let mut problems = Vec::new(); let mut prev = GENESIS.to_string(); for (i, e) in entries.iter().enumerate() { let want = i as i64 + 1; if e.seq != want { problems.push(format!("Entry {want} is missing; the next is {}.", e.seq)); } if e.prev_hash != prev { problems.push(format!( "Entry {} does not name the hash of the entry before it.", e.seq )); } if e.computed() != e.hash { problems.push(format!( "Entry {} was changed after it was written: its hash no longer matches.", e.seq )); } prev = e.hash.clone(); } // the versions against their entries #[derive(sqlx::FromRow)] struct Kept { contract_id: i64, code: String, version: i32, body: String, body_sha256: Option, file_sha256: Option, } let versions: Vec = sqlx::query_as( "SELECT v.contract_id, c.code, v.version, v.body, v.body_sha256, v.file_sha256 \ FROM contract_versions v JOIN contracts c ON c.id = v.contract_id \ ORDER BY v.id", ) .fetch_all(db) .await?; for k in versions { let (contract, code, n) = (k.contract_id, k.code, k.version); let (body, body_sha, file_sha) = (k.body, k.body_sha256, k.file_sha256); if let Some(h) = &body_sha && files::sha256_hex(body.as_bytes()) != *h { problems.push(format!( "{code} version {n}: the text no longer matches its fingerprint." )); } let tag = version_tag(n); let entry = entries.iter().find(|e| { e.contract_id == Some(contract) && e.event == "version added" && e.detail.starts_with(&tag) }); match entry { None => problems.push(format!("{code} version {n} has no entry in the journal.")), Some(e) => { for h in [&body_sha, &file_sha].into_iter().flatten() { if !e.detail.contains(h.as_str()) { problems.push(format!( "{code} version {n}: its fingerprint differs from the one in journal entry {}.", e.seq )); } } } } } let last = entries.last(); Ok(Check { entries: entries.len() as i64, head: last .map(|e| e.hash.clone()) .unwrap_or_else(|| GENESIS.to_string()), head_at: last.map(|e| e.at), problems, }) } /// How a version's entry starts: "Version 3." (the check finds it so). pub fn version_tag(n: i32) -> String { format!("Version {n}.") } /// The journal as CSV, oldest first, for a copy kept elsewhere. pub fn csv(entries: &[Entry]) -> String { fn cell(s: &str) -> String { if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } let mut out = String::from("seq,at,actor,client_id,contract_id,event,detail,prev_hash,hash\n"); for e in entries { let row = [ e.seq.to_string(), e.at.to_rfc3339_opts(SecondsFormat::Micros, true), e.actor.clone(), opt(e.client_id), opt(e.contract_id), e.event.clone(), e.detail.clone(), e.prev_hash.clone(), e.hash.clone(), ]; out.push_str(&row.iter().map(|c| cell(c)).collect::>().join(",")); out.push('\n'); } out } #[cfg(test)] mod tests { use super::*; use chrono::TimeZone; #[test] fn a_hash_names_everything_in_the_entry() { let at = Utc.with_ymd_and_hms(2026, 11, 21, 10, 0, 0).unwrap(); let h = hash_of(1, at, "alex", Some(1), None, "client added", "x", GENESIS); assert_eq!(h.len(), 64); // any part changed, a different hash assert_ne!( h, hash_of(2, at, "alex", Some(1), None, "client added", "x", GENESIS) ); assert_ne!( h, hash_of(1, at, "alexa", Some(1), None, "client added", "x", GENESIS) ); assert_ne!( h, hash_of(1, at, "alex", None, Some(1), "client added", "x", GENESIS) ); assert_ne!( h, hash_of(1, at, "alex", Some(1), None, "client added", "y", GENESIS) ); // the lengths keep the parts apart assert_ne!( hash_of(1, at, "ab", None, None, "c", "", GENESIS), hash_of(1, at, "a", None, None, "bc", "", GENESIS) ); } #[test] fn the_csv_quotes_what_needs_it() { let at = Utc.with_ymd_and_hms(2026, 11, 21, 10, 0, 0).unwrap(); let e = Entry { seq: 1, at, actor: "alex".into(), client_id: Some(2), contract_id: None, event: "client added".into(), detail: "Name: \"Demo\", Records".into(), prev_hash: GENESIS.into(), hash: GENESIS.into(), }; let c = csv(&[e]); assert!(c.contains(",\"Name: \"\"Demo\"\", Records\","), "{c}"); assert!(c.starts_with("seq,at,")); } }