Skip to main content

qualia_client_core/
accountability_ledger.rs

1//! **Tamper-evident accountability ledger** — the append-only, ed25519-**signed**, hash-**chained** store
2//! that makes the conduct + disclosure records **un-erasable (tamper-evident)** and **attributable
3//! (signed)**.
4//!
5//! ADR 0011 (D4/D5) needs the conduct trail and disclosure events to survive revocation and to resist a
6//! betrayer quietly deleting them. This module realises the "tamper-evident signed-WAL" property with **real
7//! primitives** (`sha2` + `ed25519-dalek`): each entry carries a monotone sequence, the **previous entry's
8//! hash** (the chain), a hash of its own content, and an **ed25519 signature** over that hash by the actor.
9//! Any modification, deletion, insertion, or reordering breaks a hash link or a signature, so
10//! [`AccountabilityLedger::verify`] **detects it and names the entry**.
11//!
12//! Scope: this gives tamper-**evidence** (deletion is *detectable*). Anti-deletion *durability* — that copies
13//! cannot all be removed — is the commons **replication** layer (swarm/WebTorrent; coordinate), and the two
14//! compose: replicate the ledger, and any diverging/pruned copy is provably tampered. The ledger is generic
15//! over the record kind (`"conduct"`, `"disclosure"`, `"switch"`, …) carrying serialised JSON, so it does not
16//! couple to those types.
17
18use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21
22/// The chain root — the `prev_hash` of the first entry.
23const GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";
24
25/// One ledgered, signed, chained entry.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct LedgerEntry {
28    /// Monotone position in the chain (0-based).
29    pub seq: u64,
30    /// Hash of the previous entry (or `GENESIS_HASH` for the first) — the chain link.
31    pub prev_hash_hex: String,
32    /// Hash of this entry's content (`seq ∥ prev ∥ kind ∥ payload ∥ signer ∥ time`) — the next entry chains
33    /// to it, and it is what the signature signs.
34    pub entry_hash_hex: String,
35    /// Record kind (`"conduct"`, `"disclosure"`, `"switch"`, …).
36    pub kind: String,
37    /// The serialised record (JSON).
38    pub payload_json: String,
39    /// The actor who signed (ed25519 verifying key, hex) — the attribution.
40    pub signer_pubkey_hex: String,
41    /// ed25519 signature over `entry_hash`, hex.
42    pub signature_hex: String,
43    pub time_unix: u64,
44}
45
46/// A detected tamper, naming the offending entry.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum LedgerTamper {
50    /// `prev_hash` does not match the previous entry's hash — an entry was inserted, removed, or reordered.
51    BrokenChain { seq: u64 },
52    /// The stored content hash does not match the content — the entry was modified.
53    ContentModified { seq: u64 },
54    /// The signature does not verify under the stated signer — forged or altered.
55    BadSignature { seq: u64 },
56    /// The stored seq is out of order.
57    BadSequence { seq: u64 },
58}
59
60/// An append-only, tamper-evident ledger of accountability records.
61#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
62pub struct AccountabilityLedger {
63    entries: Vec<LedgerEntry>,
64}
65
66/// Compute the content hash of an entry's fields.
67fn content_hash(
68    seq: u64,
69    prev_hash_hex: &str,
70    kind: &str,
71    payload_json: &str,
72    signer_pubkey_hex: &str,
73    time_unix: u64,
74) -> [u8; 32] {
75    let mut h = Sha256::new();
76    h.update(seq.to_le_bytes());
77    h.update(b"\x1f");
78    h.update(prev_hash_hex.as_bytes());
79    h.update(b"\x1f");
80    h.update(kind.as_bytes());
81    h.update(b"\x1f");
82    h.update(payload_json.as_bytes());
83    h.update(b"\x1f");
84    h.update(signer_pubkey_hex.as_bytes());
85    h.update(b"\x1f");
86    h.update(time_unix.to_le_bytes());
87    h.finalize().into()
88}
89
90impl AccountabilityLedger {
91    /// Creates a new instance.
92    pub fn new() -> Self {
93        Self::default()
94    }
95
96    /// Entries.
97    pub fn entries(&self) -> &[LedgerEntry] {
98        &self.entries
99    }
100    /// Length.
101    pub fn len(&self) -> usize {
102        self.entries.len()
103    }
104    /// `true` when empty.
105    pub fn is_empty(&self) -> bool {
106        self.entries.is_empty()
107    }
108
109    /// The hash the next appended entry will chain to (the last entry's hash, or genesis).
110    pub fn head_hash(&self) -> String {
111        self.entries
112            .last()
113            .map(|e| e.entry_hash_hex.clone())
114            .unwrap_or_else(|| GENESIS_HASH.to_string())
115    }
116
117    /// Append a record, **signed** by `signer` and **chained** to the current head. Returns the new entry.
118    pub fn append(
119        &mut self,
120        kind: impl Into<String>,
121        payload_json: impl Into<String>,
122        signer: &SigningKey,
123        time_unix: u64,
124    ) -> &LedgerEntry {
125        let kind = kind.into();
126        let payload_json = payload_json.into();
127        let seq = self.entries.len() as u64;
128        let prev_hash_hex = self.head_hash();
129        let signer_pubkey_hex = hex::encode(signer.verifying_key().to_bytes());
130
131        let hash = content_hash(
132            seq,
133            &prev_hash_hex,
134            &kind,
135            &payload_json,
136            &signer_pubkey_hex,
137            time_unix,
138        );
139        let signature = signer.sign(&hash);
140
141        self.entries.push(LedgerEntry {
142            seq,
143            prev_hash_hex,
144            entry_hash_hex: hex::encode(hash),
145            kind,
146            payload_json,
147            signer_pubkey_hex,
148            signature_hex: hex::encode(signature.to_bytes()),
149            time_unix,
150        });
151        self.entries.last().expect("just pushed")
152    }
153
154    /// Verify the whole chain: every entry's content hash recomputes, chains to the previous, its sequence is
155    /// in order, and its signature verifies. Returns the **first** tamper found, or `Ok(())`.
156    pub fn verify(&self) -> Result<(), LedgerTamper> {
157        let mut expected_prev = GENESIS_HASH.to_string();
158        for (i, e) in self.entries.iter().enumerate() {
159            if e.seq != i as u64 {
160                return Err(LedgerTamper::BadSequence { seq: e.seq });
161            }
162            if e.prev_hash_hex != expected_prev {
163                return Err(LedgerTamper::BrokenChain { seq: e.seq });
164            }
165            let hash = content_hash(
166                e.seq,
167                &e.prev_hash_hex,
168                &e.kind,
169                &e.payload_json,
170                &e.signer_pubkey_hex,
171                e.time_unix,
172            );
173            if hex::encode(hash) != e.entry_hash_hex {
174                return Err(LedgerTamper::ContentModified { seq: e.seq });
175            }
176            if !verify_signature(&e.signer_pubkey_hex, &hash, &e.signature_hex) {
177                return Err(LedgerTamper::BadSignature { seq: e.seq });
178            }
179            expected_prev = e.entry_hash_hex.clone();
180        }
181        Ok(())
182    }
183
184    /// Entries of a given kind (e.g. all `"conduct"`), preserving order.
185    pub fn of_kind<'a>(&'a self, kind: &str) -> Vec<&'a LedgerEntry> {
186        self.entries.iter().filter(|e| e.kind == kind).collect()
187    }
188}
189
190fn verify_signature(signer_pubkey_hex: &str, hash: &[u8; 32], signature_hex: &str) -> bool {
191    let Ok(pk_bytes) = hex::decode(signer_pubkey_hex) else {
192        return false;
193    };
194    let Ok(pk_arr): Result<[u8; 32], _> = pk_bytes.as_slice().try_into() else {
195        return false;
196    };
197    let Ok(vk) = VerifyingKey::from_bytes(&pk_arr) else {
198        return false;
199    };
200    let Ok(sig_bytes) = hex::decode(signature_hex) else {
201        return false;
202    };
203    let Ok(sig_arr): Result<[u8; 64], _> = sig_bytes.as_slice().try_into() else {
204        return false;
205    };
206    vk.verify(hash, &Signature::from_bytes(&sig_arr)).is_ok()
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    fn signer(seed: u8) -> SigningKey {
214        SigningKey::from_bytes(&[seed; 32])
215    }
216
217    #[test]
218    fn appends_are_signed_chained_and_verify() {
219        let sk = signer(1);
220        let mut led = AccountabilityLedger::new();
221        led.append("conduct", r#"{"act":"accessed record"}"#, &sk, 1_000);
222        led.append("disclosure", r#"{"to":"did:wf:mp"}"#, &sk, 1_100);
223        led.append("conduct", r#"{"act":"requested placement"}"#, &sk, 1_200);
224
225        assert_eq!(led.len(), 3);
226        assert_eq!(led.verify(), Ok(()), "a well-formed chain verifies");
227        // Each entry is attributed to its signer.
228        assert!(led
229            .entries()
230            .iter()
231            .all(|e| e.signer_pubkey_hex == hex::encode(sk.verifying_key().to_bytes())));
232        // The chain links.
233        assert_eq!(
234            led.entries()[1].prev_hash_hex,
235            led.entries()[0].entry_hash_hex
236        );
237        assert_eq!(led.of_kind("conduct").len(), 2);
238    }
239
240    #[test]
241    fn modifying_an_entrys_content_is_detected() {
242        let sk = signer(1);
243        let mut led = AccountabilityLedger::new();
244        led.append("conduct", r#"{"act":"accessed record"}"#, &sk, 1_000);
245        led.append("conduct", r#"{"act":"did nothing"}"#, &sk, 1_100);
246        // A betrayer edits the payload of entry 1 to hide what they did.
247        led.entries[1].payload_json = r#"{"act":"acted diligently"}"#.to_string();
248        assert_eq!(led.verify(), Err(LedgerTamper::ContentModified { seq: 1 }));
249    }
250
251    #[test]
252    fn deleting_an_entry_breaks_the_chain() {
253        let sk = signer(1);
254        let mut led = AccountabilityLedger::new();
255        led.append("conduct", "a", &sk, 1_000);
256        led.append("disclosure", "b", &sk, 1_100); // the inconvenient one
257        led.append("conduct", "c", &sk, 1_200);
258        // Remove the middle entry to erase evidence.
259        led.entries.remove(1);
260        // The chain breaks (seq/prev mismatch) — deletion is detectable.
261        assert!(matches!(
262            led.verify(),
263            Err(LedgerTamper::BadSequence { .. }) | Err(LedgerTamper::BrokenChain { .. })
264        ));
265    }
266
267    #[test]
268    fn a_forged_signature_is_detected() {
269        let sk = signer(1);
270        let attacker = signer(2);
271        let mut led = AccountabilityLedger::new();
272        led.append("conduct", r#"{"act":"x"}"#, &sk, 1_000);
273        // The attacker rewrites the payload AND re-signs with THEIR key + fixes the hash — but the entry now
274        // claims signer = the original actor, so the signature fails under the claimed signer.
275        let e = &mut led.entries[0];
276        e.payload_json = r#"{"act":"forged"}"#.to_string();
277        let hash = content_hash(
278            e.seq,
279            &e.prev_hash_hex,
280            &e.kind,
281            &e.payload_json,
282            &e.signer_pubkey_hex,
283            e.time_unix,
284        );
285        e.entry_hash_hex = hex::encode(hash);
286        e.signature_hex = hex::encode(attacker.sign(&hash).to_bytes()); // signed by the wrong key
287        assert_eq!(led.verify(), Err(LedgerTamper::BadSignature { seq: 0 }));
288    }
289
290    #[test]
291    fn serde_round_trips_and_still_verifies() {
292        let sk = signer(3);
293        let mut led = AccountabilityLedger::new();
294        led.append("switch", r#"{"fired":true}"#, &sk, 1_000);
295        let json = serde_json::to_string(&led).unwrap();
296        let back: AccountabilityLedger = serde_json::from_str(&json).unwrap();
297        assert_eq!(led, back);
298        assert_eq!(back.verify(), Ok(()));
299    }
300}