Skip to main content

ruvector_proof_gate/
lib.rs

1//! Proof-gated vector writes with Merkle-accumulating witness logs.
2//!
3//! Provides cryptographic write admission gates for vector stores. Every
4//! admitted write produces a `WriteReceipt` that commits the gate's current
5//! chain state. Receipts can be stored alongside vector index entries and
6//! verified offline without re-querying the write source.
7//!
8//! # Gate variants
9//!
10//! | Gate          | Per-write cost | Guarantee                          | Use case           |
11//! |---------------|----------------|------------------------------------|--------------------|
12//! | `NullGate`    | ~0 ns          | None (baseline throughput)         | Development / test |
13//! | `HashChainGate` | ~200 ns      | Sequential tamper-evidence         | Agent audit logs   |
14//! | `MerkleGate`  | ~300 ns        | MMR membership proofs + tamper-ev  | RAG provenance     |
15//!
16//! # Example
17//!
18//! ```rust
19//! use ruvector_proof_gate::{HashChainGate, WriteGate, WritePayload};
20//!
21//! let mut gate = HashChainGate::new();
22//! let payload = WritePayload::new(0, vec![0.1, 0.2, 0.3]);
23//! let receipt = gate.admit(&payload).unwrap();
24//! assert!(gate.verify_receipt(&receipt));
25//! println!("root: {:?}", gate.chain_root());
26//! ```
27
28mod gate;
29mod payload;
30
31pub use gate::{HashChainGate, MerkleGate, NullGate, WriteGate};
32pub use payload::{GateError, GateVariant, WritePayload, WriteReceipt};
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use crate::gate::{HashChainGate, MerkleGate, NullGate, WriteGate};
38
39    fn make_payload(id: u64) -> WritePayload {
40        WritePayload::new(id, vec![id as f32 * 0.1, id as f32 * 0.2, id as f32 * 0.3])
41    }
42
43    // ── NullGate ─────────────────────────────────────────────────────────────
44
45    #[test]
46    fn null_gate_admits_all() {
47        let mut g = NullGate::new();
48        for i in 0..10u64 {
49            let r = g.admit(&make_payload(i)).unwrap();
50            assert_eq!(r.sequence, i);
51            assert_eq!(r.gate_variant, GateVariant::Null);
52        }
53        assert_eq!(g.len(), 10);
54    }
55
56    #[test]
57    fn null_gate_verify_always_true() {
58        let mut g = NullGate::new();
59        let r = g.admit(&make_payload(0)).unwrap();
60        assert!(g.verify_receipt(&r));
61    }
62
63    // ── HashChainGate ─────────────────────────────────────────────────────────
64
65    #[test]
66    fn hash_chain_receipts_are_unique() {
67        let mut g = HashChainGate::new();
68        let r0 = g.admit(&make_payload(0)).unwrap();
69        let r1 = g.admit(&make_payload(1)).unwrap();
70        // Different payloads → different chain commitments
71        assert_ne!(r0.chain_commitment, r1.chain_commitment);
72        // Different sequence numbers
73        assert_eq!(r0.sequence, 0);
74        assert_eq!(r1.sequence, 1);
75    }
76
77    #[test]
78    fn hash_chain_verify_receipts() {
79        let mut g = HashChainGate::new();
80        let receipts: Vec<_> = (0..20u64).map(|i| g.admit(&make_payload(i)).unwrap()).collect();
81        for r in &receipts {
82            assert!(g.verify_receipt(r), "receipt {} failed verification", r.sequence);
83        }
84    }
85
86    #[test]
87    fn hash_chain_root_non_zero_after_writes() {
88        let mut g = HashChainGate::new();
89        g.admit(&make_payload(0)).unwrap();
90        assert_ne!(g.chain_root(), [0u8; 32]);
91    }
92
93    #[test]
94    fn hash_chain_same_payload_same_commitment_chain() {
95        // Two identical payloads admitted sequentially produce different
96        // chain commitments because the chain prev-hash differs.
97        let mut g = HashChainGate::new();
98        let p = make_payload(42);
99        let r0 = g.admit(&p).unwrap();
100        let r1 = g.admit(&p).unwrap();
101        assert_ne!(r0.chain_commitment, r1.chain_commitment);
102    }
103
104    // ── MerkleGate ────────────────────────────────────────────────────────────
105
106    #[test]
107    fn merkle_gate_roots_change_on_each_write() {
108        let mut g = MerkleGate::new();
109        let mut roots = Vec::new();
110        for i in 0..8u64 {
111            g.admit(&make_payload(i)).unwrap();
112            roots.push(g.chain_root());
113        }
114        // All roots must be distinct (each write changes the MMR)
115        let unique: std::collections::HashSet<_> = roots.iter().collect();
116        assert_eq!(unique.len(), 8, "expected 8 distinct roots");
117    }
118
119    #[test]
120    fn merkle_gate_verify_receipts() {
121        let mut g = MerkleGate::new();
122        let receipts: Vec<_> = (0..20u64).map(|i| g.admit(&make_payload(i)).unwrap()).collect();
123        for r in &receipts {
124            assert!(g.verify_receipt(r), "receipt {} failed", r.sequence);
125        }
126    }
127
128    #[test]
129    fn merkle_gate_root_non_zero_after_writes() {
130        let mut g = MerkleGate::new();
131        g.admit(&make_payload(0)).unwrap();
132        assert_ne!(g.chain_root(), [0u8; 32]);
133    }
134
135    #[test]
136    fn merkle_gate_power_of_two_leaves_stable() {
137        // For 2^k leaves the MMR collapses to a single peak (complete binary tree).
138        let mut g = MerkleGate::new();
139        for i in 0..8u64 {
140            g.admit(&make_payload(i)).unwrap();
141        }
142        // After 8 = 2^3 leaves the peaks vec should have exactly 1 entry.
143        // We can't inspect peaks directly, but we CAN verify the root is stable
144        // across a re-read without new writes.
145        let root_a = g.chain_root();
146        let root_b = g.chain_root();
147        assert_eq!(root_a, root_b, "root must be deterministic");
148    }
149
150    // ── synthetic_payloads ───────────────────────────────────────────────────
151
152    #[test]
153    fn synthetic_payloads_length_and_dims() {
154        let ps = synthetic_payloads(100, 64);
155        assert_eq!(ps.len(), 100);
156        assert!(ps.iter().all(|p| p.vector.len() == 64));
157    }
158
159    #[test]
160    fn synthetic_payloads_deterministic() {
161        let a = synthetic_payloads(50, 32);
162        let b = synthetic_payloads(50, 32);
163        assert!(a.iter().zip(b.iter()).all(|(x, y)| x.vector == y.vector));
164    }
165
166    // ── Acceptance: functional correctness at scale ────────────────────────
167
168    #[test]
169    fn acceptance_hash_chain_bulk_verify() {
170        // 500 writes → all receipts must verify correctly.
171        let payloads = synthetic_payloads(500, 64);
172        let mut gate = HashChainGate::new();
173        let receipts: Vec<_> = payloads.iter().map(|p| gate.admit(p).unwrap()).collect();
174        let all_ok = receipts.iter().all(|r| gate.verify_receipt(r));
175        assert!(all_ok, "bulk receipt verification failed for HashChainGate");
176        assert_eq!(gate.len(), 500);
177        assert_ne!(gate.chain_root(), [0u8; 32]);
178    }
179
180    #[test]
181    fn acceptance_merkle_bulk_verify() {
182        // 500 writes → all receipts must verify correctly.
183        let payloads = synthetic_payloads(500, 64);
184        let mut gate = MerkleGate::new();
185        let receipts: Vec<_> = payloads.iter().map(|p| gate.admit(p).unwrap()).collect();
186        let all_ok = receipts.iter().all(|r| gate.verify_receipt(r));
187        assert!(all_ok, "bulk receipt verification failed for MerkleGate");
188        assert_eq!(gate.len(), 500);
189        assert_ne!(gate.chain_root(), [0u8; 32]);
190    }
191
192    #[test]
193    fn acceptance_all_gates_distinct_roots() {
194        // With the same payloads, NullGate returns zero root while
195        // HashChain and Merkle return non-zero, non-equal roots.
196        let payloads = synthetic_payloads(16, 32);
197        let mut null = NullGate::new();
198        let mut chain = HashChainGate::new();
199        let mut merkle = MerkleGate::new();
200        for p in &payloads {
201            null.admit(p).unwrap();
202            chain.admit(p).unwrap();
203            merkle.admit(p).unwrap();
204        }
205        assert_eq!(null.chain_root(), [0u8; 32], "NullGate root must be zero");
206        assert_ne!(chain.chain_root(), [0u8; 32], "HashChain root must be non-zero");
207        assert_ne!(merkle.chain_root(), [0u8; 32], "Merkle root must be non-zero");
208        // HashChain and Merkle roots differ (different algorithms)
209        assert_ne!(
210            chain.chain_root(),
211            merkle.chain_root(),
212            "HashChain and Merkle roots must differ"
213        );
214    }
215}
216
217/// Generate a deterministic synthetic dataset for benchmarks.
218///
219/// Returns `n` payloads with `dims`-dimensional f32 vectors. Uses a simple
220/// LCG so benchmarks are reproducible without an external RNG dependency.
221pub fn synthetic_payloads(n: usize, dims: usize) -> Vec<WritePayload> {
222    let mut state: u64 = 0x6b37_9d3c_2a85_f1e4;
223    let mut next = move || -> f32 {
224        // Xorshift64
225        state ^= state << 13;
226        state ^= state >> 7;
227        state ^= state << 17;
228        // Map to [-1, 1]
229        (state as i64 as f64 / i64::MAX as f64) as f32
230    };
231
232    (0..n)
233        .map(|i| {
234            let vector: Vec<f32> = (0..dims).map(|_| next()).collect();
235            WritePayload::new(i as u64, vector)
236        })
237        .collect()
238}