Skip to main content

ruvector_proof_gate/
gate.rs

1use sha2::{Digest, Sha256};
2
3use crate::payload::{GateError, GateVariant, WritePayload, WriteReceipt};
4
5// ─────────────────────────────────────────────────────────────────────────────
6// WriteGate trait
7// ─────────────────────────────────────────────────────────────────────────────
8
9/// Core admission gate trait for vector writes.
10///
11/// Each gate variant encapsulates one integrity strategy. Callers insert a
12/// `WritePayload` and receive a `WriteReceipt` that commits the gate's
13/// current chain state. Receipts can be stored alongside the vector index
14/// entry and verified offline.
15pub trait WriteGate: Send + Sync {
16    /// Admit a payload and return a tamper-evident receipt.
17    fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError>;
18
19    /// Verify that a receipt is consistent with the gate's internal state.
20    fn verify_receipt(&self, receipt: &WriteReceipt) -> bool;
21
22    /// Current chain commitment (root or chain head). Changes after every
23    /// successful `admit()`.
24    fn chain_root(&self) -> [u8; 32];
25
26    /// Number of writes admitted so far.
27    fn len(&self) -> usize;
28
29    /// Returns true if no writes have been admitted.
30    fn is_empty(&self) -> bool {
31        self.len() == 0
32    }
33
34    /// Gate variant identifier.
35    fn variant(&self) -> GateVariant;
36}
37
38// ─────────────────────────────────────────────────────────────────────────────
39// NullGate — baseline, no hashing overhead
40// ─────────────────────────────────────────────────────────────────────────────
41
42/// No-op gate that admits every payload with zero cryptographic overhead.
43/// Used exclusively to establish a throughput ceiling for comparison.
44pub struct NullGate {
45    seq: u64,
46}
47
48impl NullGate {
49    pub fn new() -> Self {
50        Self { seq: 0 }
51    }
52}
53
54impl Default for NullGate {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl WriteGate for NullGate {
61    fn admit(&mut self, _payload: &WritePayload) -> Result<WriteReceipt, GateError> {
62        let seq = self.seq;
63        self.seq += 1;
64        Ok(WriteReceipt {
65            sequence: seq,
66            payload_hash: [0u8; 32],
67            chain_commitment: [0u8; 32],
68            gate_variant: GateVariant::Null,
69        })
70    }
71
72    fn verify_receipt(&self, _receipt: &WriteReceipt) -> bool {
73        true
74    }
75
76    fn chain_root(&self) -> [u8; 32] {
77        [0u8; 32]
78    }
79
80    fn len(&self) -> usize {
81        self.seq as usize
82    }
83
84    fn variant(&self) -> GateVariant {
85        GateVariant::Null
86    }
87}
88
89// ─────────────────────────────────────────────────────────────────────────────
90// HashChainGate — O(1) per write, sequential SHA-256 chain
91// ─────────────────────────────────────────────────────────────────────────────
92
93/// Sequential SHA-256 hash chain.
94///
95/// Each write links to its predecessor: commitment[n] = SHA256(commitment[n-1]
96/// || payload_hash[n] || n). An adversary cannot silently mutate, reorder, or
97/// delete any entry without invalidating all subsequent commitments.
98/// Verification is O(n): replay the chain from the beginning.
99///
100/// Memory: 64 bytes per admitted write (commitment + payload hash, both needed
101/// to cryptographically re-derive the chain).
102pub struct HashChainGate {
103    seq: u64,
104    prev_commitment: [u8; 32],
105    // Per-entry chain commitments.
106    chain: Vec<[u8; 32]>,
107    // Per-entry payload hashes — required to *re-derive* (not merely structurally
108    // scan) the chain in `verify_integrity`.
109    payload_hashes: Vec<[u8; 32]>,
110}
111
112/// Genesis seed = SHA256("ruvector-proof-gate-v1"). The re-derivation anchor.
113const GENESIS: [u8; 32] = *b"\xb7\x4c\x9b\x41\x3e\x27\x0e\x56\
114                            \xd3\x8a\x12\x9f\x6c\x3b\x4d\x8a\
115                            \x2f\x1e\x0c\x5a\x9d\x7b\xe4\xf2\
116                            \x6a\x8c\x3d\x0b\x5e\x9f\x2c\x47";
117
118impl HashChainGate {
119    pub fn new() -> Self {
120        Self {
121            seq: 0,
122            prev_commitment: GENESIS,
123            chain: Vec::new(),
124            payload_hashes: Vec::new(),
125        }
126    }
127
128    fn compute_commitment(prev: &[u8; 32], payload_hash: &[u8; 32], seq: u64) -> [u8; 32] {
129        let mut h = Sha256::new();
130        h.update(b"ruvector:chain:");
131        h.update(prev);
132        h.update(payload_hash);
133        h.update(&seq.to_le_bytes());
134        h.finalize().into()
135    }
136
137    /// Full cryptographic chain re-derivation. Re-computes every commitment from
138    /// the genesis seed and the stored payload hashes, comparing against the
139    /// stored chain. Returns false if ANY commitment fails to re-derive — i.e.
140    /// catches a tamper that mutates a commitment, a payload hash, or the order,
141    /// not just structurally-degenerate chains.
142    pub fn verify_integrity(&self) -> bool {
143        if self.chain.len() != self.payload_hashes.len() {
144            return false;
145        }
146        let mut prev = GENESIS;
147        for (i, (commitment, payload_hash)) in
148            self.chain.iter().zip(self.payload_hashes.iter()).enumerate()
149        {
150            let expected = Self::compute_commitment(&prev, payload_hash, i as u64);
151            if &expected != commitment {
152                return false;
153            }
154            prev = *commitment;
155        }
156        // Chain head must equal the last commitment (or genesis if empty).
157        self.prev_commitment == prev
158    }
159}
160
161impl Default for HashChainGate {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl WriteGate for HashChainGate {
168    fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError> {
169        // Allocation-free payload hash (identical digest to hashing canonical_bytes).
170        let payload_hash: [u8; 32] = payload.payload_hash();
171        let commitment = Self::compute_commitment(&self.prev_commitment, &payload_hash, self.seq);
172        self.prev_commitment = commitment;
173        self.chain.push(commitment);
174        self.payload_hashes.push(payload_hash);
175        let seq = self.seq;
176        self.seq += 1;
177        Ok(WriteReceipt {
178            sequence: seq,
179            payload_hash,
180            chain_commitment: commitment,
181            gate_variant: GateVariant::HashChain,
182        })
183    }
184
185    fn verify_receipt(&self, receipt: &WriteReceipt) -> bool {
186        let idx = receipt.sequence as usize;
187        idx < self.chain.len() && self.chain[idx] == receipt.chain_commitment
188    }
189
190    fn chain_root(&self) -> [u8; 32] {
191        self.prev_commitment
192    }
193
194    fn len(&self) -> usize {
195        self.seq as usize
196    }
197
198    fn variant(&self) -> GateVariant {
199        GateVariant::HashChain
200    }
201}
202
203// ─────────────────────────────────────────────────────────────────────────────
204// MerkleGate — Merkle Mountain Range, O(log n) amortized per write
205// ─────────────────────────────────────────────────────────────────────────────
206
207/// Merkle Mountain Range (MMR) accumulator.
208///
209/// An MMR maintains a forest of perfect binary trees. Appending a leaf is
210/// O(log n) amortized: binary representations of the leaf count determine
211/// which existing peaks must be merged. The "bagged" root (fold of all
212/// peaks) changes with every write.
213///
214/// Compared to `HashChainGate`:
215/// - Same tamper-evidence guarantee (mutating any leaf changes the root).
216/// - Supports Merkle inclusion proofs (proof that leaf N is in the set)
217///   without replaying the entire chain.
218/// - Slightly higher per-write overhead due to peak management.
219///
220/// Memory: ~2n * 32 bytes (peaks + leaf hashes stored for membership proofs).
221pub struct MerkleGate {
222    seq: u64,
223    /// MMR peaks ordered lowest-level-first.
224    /// peaks[i] covers a subtree with 2^level[i] leaves.
225    peaks: Vec<[u8; 32]>,
226    /// Total leaves inserted (determines peak structure via binary representation).
227    leaf_count: u64,
228    /// Leaf hashes stored for membership proof generation.
229    leaves: Vec<[u8; 32]>,
230}
231
232impl MerkleGate {
233    pub fn new() -> Self {
234        Self {
235            seq: 0,
236            peaks: Vec::new(),
237            leaf_count: 0,
238            leaves: Vec::new(),
239        }
240    }
241
242    fn hash_pair(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
243        let mut h = Sha256::new();
244        h.update(b"ruvector:mmr:");
245        h.update(left);
246        h.update(right);
247        h.finalize().into()
248    }
249
250    fn leaf_commit(payload_hash: &[u8; 32], seq: u64) -> [u8; 32] {
251        let mut h = Sha256::new();
252        h.update(b"ruvector:leaf:");
253        h.update(payload_hash);
254        h.update(&seq.to_le_bytes());
255        h.finalize().into()
256    }
257
258    /// Append a leaf to the MMR. O(log n) amortized.
259    fn append(&mut self, leaf: [u8; 32]) {
260        let mut node = leaf;
261        let mut n = self.leaf_count;
262        // While the trailing bit of n is 1, merge with the last peak.
263        while n & 1 == 1 {
264            let peak = self.peaks.pop().expect("peak must exist when bit is set");
265            node = Self::hash_pair(&peak, &node);
266            n >>= 1;
267        }
268        self.peaks.push(node);
269        self.leaf_count += 1;
270    }
271
272    /// Bag all peaks into a single root by folding left-to-right.
273    fn bagged_root(&self) -> [u8; 32] {
274        if self.peaks.is_empty() {
275            return [0u8; 32];
276        }
277        // Fold from highest-order peak (leftmost in tree) to lowest.
278        let mut acc = self.peaks[0];
279        for peak in &self.peaks[1..] {
280            acc = Self::hash_pair(&acc, peak);
281        }
282        acc
283    }
284
285    /// Verify that the leaf at `sequence` matches the stored leaf hash.
286    /// Full inclusion proof generation is left for the production crate.
287    pub fn verify_leaf(&self, sequence: u64, payload_hash: &[u8; 32]) -> bool {
288        let idx = sequence as usize;
289        if idx >= self.leaves.len() {
290            return false;
291        }
292        let expected = Self::leaf_commit(payload_hash, sequence);
293        self.leaves[idx] == expected
294    }
295}
296
297impl Default for MerkleGate {
298    fn default() -> Self {
299        Self::new()
300    }
301}
302
303impl WriteGate for MerkleGate {
304    fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError> {
305        // Allocation-free payload hash (identical digest to hashing canonical_bytes).
306        let payload_hash: [u8; 32] = payload.payload_hash();
307        let leaf = Self::leaf_commit(&payload_hash, self.seq);
308        self.leaves.push(leaf);
309        self.append(leaf);
310        let root = self.bagged_root();
311        let seq = self.seq;
312        self.seq += 1;
313        Ok(WriteReceipt {
314            sequence: seq,
315            payload_hash,
316            chain_commitment: root,
317            gate_variant: GateVariant::Merkle,
318        })
319    }
320
321    fn verify_receipt(&self, receipt: &WriteReceipt) -> bool {
322        self.verify_leaf(receipt.sequence, &receipt.payload_hash)
323    }
324
325    fn chain_root(&self) -> [u8; 32] {
326        self.bagged_root()
327    }
328
329    fn len(&self) -> usize {
330        self.seq as usize
331    }
332
333    fn variant(&self) -> GateVariant {
334        GateVariant::Merkle
335    }
336}
337
338#[cfg(test)]
339mod rederivation_tests {
340    use super::*;
341    use crate::WritePayload;
342
343    fn gate_with(n: u64) -> HashChainGate {
344        let mut g = HashChainGate::new();
345        for i in 0..n {
346            g.admit(&WritePayload::new(i, vec![i as f32, 1.0, -(i as f32)])).unwrap();
347        }
348        g
349    }
350
351    #[test]
352    fn clean_chain_reverifies() {
353        assert!(gate_with(8).verify_integrity());
354        assert!(HashChainGate::new().verify_integrity(), "empty chain is valid");
355    }
356
357    #[test]
358    fn tampered_commitment_detected() {
359        let mut g = gate_with(8);
360        g.chain[3][0] ^= 0xFF; // flip a byte of a stored commitment
361        assert!(!g.verify_integrity(), "mutated commitment must fail re-derivation");
362    }
363
364    #[test]
365    fn tampered_payload_hash_detected() {
366        let mut g = gate_with(8);
367        g.payload_hashes[2][0] ^= 0xFF; // poisoned write whose recorded hash no longer matches
368        assert!(!g.verify_integrity(), "mutated payload hash must fail re-derivation");
369    }
370
371    #[test]
372    fn reordered_entries_detected() {
373        let mut g = gate_with(8);
374        g.chain.swap(2, 5);
375        g.payload_hashes.swap(2, 5);
376        assert!(!g.verify_integrity(), "reordering entries must fail re-derivation");
377    }
378
379    #[test]
380    fn length_mismatch_detected() {
381        let mut g = gate_with(8);
382        g.payload_hashes.pop();
383        assert!(!g.verify_integrity());
384    }
385}