Skip to main content

photonlayer_ruvector/
receipts.rs

1//! RVF-style receipt store and verification (ADR-260 ยง15).
2//!
3//! [`ReceiptStore`] persists receipts as JSON strings and delegates
4//! verification to [`photonlayer_core::receipt::verify_receipt`].
5
6use photonlayer_core::prelude::{verify_receipt, ExperimentReceipt};
7use serde_json;
8use std::collections::HashMap;
9
10/// Storage and verification of [`ExperimentReceipt`]s.
11///
12/// Each receipt is serialised to JSON on insertion so that the raw bytes
13/// remain stable. Verification deserialises and recomputes the binding digest.
14#[derive(Default, Debug)]
15pub struct ReceiptStore {
16    /// Map from `experiment_id` to serialised JSON string.
17    store: HashMap<String, String>,
18}
19
20impl ReceiptStore {
21    /// Create an empty receipt store.
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// Insert a receipt, overwriting any existing entry for the same id.
27    ///
28    /// # Errors
29    /// Returns an error string if serialisation fails (practically infallible
30    /// for well-formed receipts).
31    pub fn insert(&mut self, receipt: &ExperimentReceipt) -> Result<(), String> {
32        let json = serde_json::to_string(receipt).map_err(|e| format!("serialise failed: {e}"))?;
33        self.store.insert(receipt.experiment_id.clone(), json);
34        Ok(())
35    }
36
37    /// Number of stored receipts.
38    pub fn len(&self) -> usize {
39        self.store.len()
40    }
41
42    /// Returns `true` when no receipts are stored.
43    pub fn is_empty(&self) -> bool {
44        self.store.is_empty()
45    }
46
47    /// Verify the receipt identified by `id`.
48    ///
49    /// Returns `true` if the receipt passes [`verify_receipt`].
50    /// Returns `false` if the id is unknown, deserialisation fails, or
51    /// verification fails (tampered fields).
52    pub fn verify(&self, id: &str) -> bool {
53        match self.store.get(id) {
54            None => false,
55            Some(json) => match serde_json::from_str::<ExperimentReceipt>(json) {
56                Err(_) => false,
57                Ok(receipt) => verify_receipt(&receipt),
58            },
59        }
60    }
61
62    /// Verify every stored receipt.
63    ///
64    /// Returns a map from experiment id to verification outcome.
65    pub fn verify_all(&self) -> HashMap<String, bool> {
66        self.store
67            .iter()
68            .map(|(id, json)| {
69                let ok = serde_json::from_str::<ExperimentReceipt>(json)
70                    .map(|r| verify_receipt(&r))
71                    .unwrap_or(false);
72                (id.clone(), ok)
73            })
74            .collect()
75    }
76
77    /// Retrieve the stored JSON string for an experiment id.
78    pub fn get_json(&self, id: &str) -> Option<&str> {
79        self.store.get(id).map(String::as_str)
80    }
81
82    /// Retrieve and deserialise a receipt by experiment id.
83    ///
84    /// Returns `None` if the id is unknown or deserialisation fails.
85    pub fn get(&self, id: &str) -> Option<ExperimentReceipt> {
86        self.store
87            .get(id)
88            .and_then(|json| serde_json::from_str(json).ok())
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use photonlayer_core::prelude::{
96        build_receipt, InputImage, MetricReport, OpticalConfig, OpticalSimulator, PhaseMask,
97        Provenance, ScalarSimulator,
98    };
99
100    fn make_receipt(id: &str, seed: u64) -> ExperimentReceipt {
101        let n = 16;
102        let pixels: Vec<f32> = (0..n * n).map(|i| (i % n) as f32 / n as f32).collect();
103        let img = InputImage::from_norm_f32(n, n, pixels).unwrap();
104        let mask = PhaseMask::random(n, n, seed);
105        let cfg = OpticalConfig::demo(n, n);
106        let frame = ScalarSimulator.simulate(&img, &mask, &cfg).unwrap();
107        let metrics = MetricReport::default();
108        build_receipt(
109            id,
110            &img,
111            &mask,
112            &cfg,
113            &frame,
114            &metrics,
115            &Provenance::default(),
116        )
117    }
118
119    #[test]
120    fn insert_and_verify_valid_receipt() {
121        let mut store = ReceiptStore::new();
122        let r = make_receipt("exp-ok", 1);
123        store.insert(&r).unwrap();
124        assert!(store.verify("exp-ok"), "valid receipt should verify");
125    }
126
127    #[test]
128    fn verify_unknown_id_returns_false() {
129        let store = ReceiptStore::new();
130        assert!(!store.verify("nonexistent"));
131    }
132
133    #[test]
134    fn tampered_receipt_fails_verification() {
135        let mut store = ReceiptStore::new();
136        let mut r = make_receipt("exp-tampered", 2);
137        // Tamper: mutate a hash field after building.
138        r.output_hash.push('X');
139        store.insert(&r).unwrap();
140        assert!(!store.verify("exp-tampered"), "tampered receipt must fail");
141    }
142
143    #[test]
144    fn verify_all_mixes_pass_and_fail() {
145        let mut store = ReceiptStore::new();
146        let good = make_receipt("good", 3);
147        store.insert(&good).unwrap();
148
149        // Insert a deliberately broken receipt by mutating JSON after insertion.
150        let mut bad = make_receipt("bad", 4);
151        bad.mask_hash.push('!');
152        store.insert(&bad).unwrap();
153
154        let results = store.verify_all();
155        assert_eq!(results.len(), 2);
156        assert!(results["good"]);
157        assert!(!results["bad"]);
158    }
159
160    #[test]
161    fn len_and_is_empty() {
162        let mut store = ReceiptStore::new();
163        assert!(store.is_empty());
164        store.insert(&make_receipt("e1", 5)).unwrap();
165        assert_eq!(store.len(), 1);
166        store.insert(&make_receipt("e2", 6)).unwrap();
167        assert_eq!(store.len(), 2);
168    }
169}