1use quantaegis_core::{Error, Result, Zeroize};
12
13pub const STARTUP_SAMPLE_COUNT: usize = 1_024;
16
17pub const APT_NON_BINARY_WINDOW: usize = 512;
20
21pub const APT_BINARY_WINDOW: usize = 1_024;
24
25#[derive(Copy, Clone, Debug, Eq, PartialEq)]
27pub enum AptSourceKind {
28 Binary,
30 NonBinary,
32}
33
34impl AptSourceKind {
35 #[inline]
37 pub const fn window_size(self) -> usize {
38 match self {
39 Self::Binary => APT_BINARY_WINDOW,
40 Self::NonBinary => APT_NON_BINARY_WINDOW,
41 }
42 }
43}
44
45pub struct RepetitionCountTest {
50 cutoff: u32,
51 last_sample: u64,
52 run_count: u32,
53 initialized: bool,
54 failed: bool,
55}
56
57impl RepetitionCountTest {
58 pub const fn new(cutoff: u32) -> Result<Self> {
61 if cutoff < 2 {
62 return Err(Error::DrbgInvalidRequest);
63 }
64 Ok(Self {
65 cutoff,
66 last_sample: 0,
67 run_count: 0,
68 initialized: false,
69 failed: false,
70 })
71 }
72
73 pub fn observe(&mut self, sample: u64) -> Result<()> {
77 if self.failed {
78 return Err(Error::EntropyHealthCheckFailed);
79 }
80 if !self.initialized {
81 self.last_sample = sample;
82 self.run_count = 1;
83 self.initialized = true;
84 return Ok(());
85 }
86 if sample == self.last_sample {
87 self.run_count = self.run_count.saturating_add(1);
88 if self.run_count >= self.cutoff {
89 self.failed = true;
90 return Err(Error::EntropyHealthCheckFailed);
91 }
92 } else {
93 self.last_sample = sample;
94 self.run_count = 1;
95 }
96 Ok(())
97 }
98
99 #[inline]
101 pub const fn is_failed(&self) -> bool {
102 self.failed
103 }
104}
105
106impl Zeroize for RepetitionCountTest {
107 #[inline]
108 fn zeroize(&mut self) {
109 self.last_sample = 0;
110 self.run_count = 0;
111 self.initialized = false;
112 }
113}
114
115impl Drop for RepetitionCountTest {
116 #[inline]
117 fn drop(&mut self) {
118 self.zeroize();
119 }
120}
121
122pub struct AdaptiveProportionTest {
128 window_size: usize,
129 cutoff: u32,
130 reference_sample: u64,
131 matches_in_window: u32,
132 samples_in_window: usize,
133 failed: bool,
134}
135
136impl AdaptiveProportionTest {
137 pub const fn new(window_size: usize, cutoff: u32) -> Result<Self> {
143 if window_size < 2 || cutoff < 2 || (cutoff as usize) > window_size {
144 return Err(Error::DrbgInvalidRequest);
145 }
146 Ok(Self {
147 window_size,
148 cutoff,
149 reference_sample: 0,
150 matches_in_window: 0,
151 samples_in_window: 0,
152 failed: false,
153 })
154 }
155
156 pub const fn for_source_kind(kind: AptSourceKind, cutoff: u32) -> Result<Self> {
158 Self::new(kind.window_size(), cutoff)
159 }
160
161 pub fn observe(&mut self, sample: u64) -> Result<()> {
165 if self.failed {
166 return Err(Error::EntropyHealthCheckFailed);
167 }
168 if self.samples_in_window == 0 {
169 self.reference_sample = sample;
170 self.matches_in_window = 1;
171 self.samples_in_window = 1;
172 return Ok(());
173 }
174
175 if sample == self.reference_sample {
176 self.matches_in_window = self.matches_in_window.saturating_add(1);
177 if self.matches_in_window >= self.cutoff {
178 self.failed = true;
179 return Err(Error::EntropyHealthCheckFailed);
180 }
181 }
182
183 self.samples_in_window += 1;
184 if self.samples_in_window >= self.window_size {
185 self.samples_in_window = 0;
186 self.matches_in_window = 0;
187 self.reference_sample = 0;
188 }
189 Ok(())
190 }
191
192 #[inline]
194 pub const fn is_failed(&self) -> bool {
195 self.failed
196 }
197}
198
199impl Zeroize for AdaptiveProportionTest {
200 #[inline]
201 fn zeroize(&mut self) {
202 self.reference_sample = 0;
203 self.matches_in_window = 0;
204 self.samples_in_window = 0;
205 }
206}
207
208impl Drop for AdaptiveProportionTest {
209 #[inline]
210 fn drop(&mut self) {
211 self.zeroize();
212 }
213}
214
215pub struct RawNoiseHealthMonitor {
222 rct: RepetitionCountTest,
223 apt: AdaptiveProportionTest,
224 startup_passed: usize,
225 failed: bool,
226}
227
228impl RawNoiseHealthMonitor {
229 pub fn new(rct_cutoff: u32, kind: AptSourceKind, apt_cutoff: u32) -> Result<Self> {
232 let rct = RepetitionCountTest::new(rct_cutoff)?;
233 let apt = AdaptiveProportionTest::for_source_kind(kind, apt_cutoff)?;
234 Ok(Self {
235 rct,
236 apt,
237 startup_passed: 0,
238 failed: false,
239 })
240 }
241
242 pub fn observe(&mut self, sample: u64) -> Result<bool> {
249 if self.failed {
250 return Err(Error::EntropyHealthCheckFailed);
251 }
252 if self.rct.observe(sample).is_err() || self.apt.observe(sample).is_err() {
253 self.failed = true;
254 return Err(Error::EntropyHealthCheckFailed);
255 }
256 if self.startup_passed < STARTUP_SAMPLE_COUNT {
257 self.startup_passed += 1;
258 }
259 Ok(self.is_ready())
260 }
261
262 pub fn run_on_demand_test(&mut self, samples: &[u64]) -> Result<()> {
265 if self.failed {
266 return Err(Error::EntropyHealthCheckFailed);
267 }
268 if samples.len() < STARTUP_SAMPLE_COUNT {
269 return Err(Error::DrbgInvalidRequest);
270 }
271 for &sample in samples {
272 if self.observe(sample).is_err() {
273 return Err(Error::EntropyHealthCheckFailed);
274 }
275 }
276 Ok(())
277 }
278
279 #[inline]
281 pub const fn is_ready(&self) -> bool {
282 !self.failed && self.startup_passed >= STARTUP_SAMPLE_COUNT
283 }
284
285 #[inline]
287 pub const fn is_failed(&self) -> bool {
288 self.failed
289 }
290}
291
292impl Zeroize for RawNoiseHealthMonitor {
293 #[inline]
294 fn zeroize(&mut self) {
295 self.rct.zeroize();
296 self.apt.zeroize();
297 self.startup_passed = 0;
298 }
299}
300
301impl Drop for RawNoiseHealthMonitor {
302 #[inline]
303 fn drop(&mut self) {
304 self.zeroize();
305 }
306}
307
308pub fn run_raw_noise_health_test(
311 samples: &[u64],
312 rct_cutoff: u32,
313 apt_window: usize,
314 apt_cutoff: u32,
315) -> Result<()> {
316 if samples.len() < STARTUP_SAMPLE_COUNT {
317 return Err(Error::DrbgInvalidRequest);
318 }
319 let mut rct = RepetitionCountTest::new(rct_cutoff)?;
320 let mut apt = AdaptiveProportionTest::new(apt_window, apt_cutoff)?;
321 for &sample in samples {
322 rct.observe(sample)?;
323 apt.observe(sample)?;
324 }
325 Ok(())
326}
327
328#[cfg(test)]
329#[allow(clippy::expect_used)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn rct_triggers_at_exact_cutoff_and_latches() {
335 let mut rct = RepetitionCountTest::new(4).expect("valid cutoff");
336 assert_eq!(rct.observe(7), Ok(()));
337 assert_eq!(rct.observe(7), Ok(()));
338 assert_eq!(rct.observe(7), Ok(()));
339 assert_eq!(rct.observe(7), Err(Error::EntropyHealthCheckFailed));
340 assert!(rct.is_failed());
341 assert_eq!(rct.observe(8), Err(Error::EntropyHealthCheckFailed));
342 }
343
344 #[test]
345 fn apt_triggers_on_exact_last_sample_of_window_and_resets_otherwise() {
346 let mut apt = AdaptiveProportionTest::new(4, 3).expect("valid apt");
348 assert_eq!(apt.observe(9), Ok(()));
349 assert_eq!(apt.observe(9), Ok(()));
350 assert_eq!(apt.observe(1), Ok(()));
351 assert_eq!(apt.observe(9), Err(Error::EntropyHealthCheckFailed));
352 assert!(apt.is_failed());
353 assert_eq!(apt.observe(2), Err(Error::EntropyHealthCheckFailed));
354
355 let mut apt2 = AdaptiveProportionTest::new(4, 3).expect("valid apt");
357 assert_eq!(apt2.observe(9), Ok(()));
358 assert_eq!(apt2.observe(1), Ok(()));
359 assert_eq!(apt2.observe(9), Ok(()));
360 assert_eq!(apt2.observe(2), Ok(()));
361 assert_eq!(apt2.observe(5), Ok(()));
362 assert_eq!(apt2.observe(5), Ok(()));
363 assert_eq!(apt2.observe(5), Err(Error::EntropyHealthCheckFailed));
364 }
365
366 #[test]
367 fn startup_monitor_blocks_until_1024_and_catches_failure_on_1024th_sample() {
368 let mut mon_fail =
370 RawNoiseHealthMonitor::new(4, AptSourceKind::NonBinary, 325).expect("valid monitor");
371 for i in 0..1_020u64 {
372 assert_eq!(mon_fail.observe(i & 0xff), Ok(false));
373 assert!(!mon_fail.is_ready());
374 }
375 assert_eq!(mon_fail.observe(0xfe), Ok(false));
376 assert_eq!(mon_fail.observe(0xfe), Ok(false));
377 assert_eq!(mon_fail.observe(0xfe), Ok(false));
378 assert_eq!(mon_fail.observe(0xfe), Err(Error::EntropyHealthCheckFailed));
380 assert!(mon_fail.is_failed());
381 assert!(!mon_fail.is_ready());
382 assert_eq!(mon_fail.observe(0x01), Err(Error::EntropyHealthCheckFailed));
383
384 let mut mon_ok =
386 RawNoiseHealthMonitor::new(4, AptSourceKind::NonBinary, 325).expect("valid monitor");
387 for i in 0..1_023u64 {
388 assert_eq!(mon_ok.observe(i & 0xff), Ok(false));
389 }
390 assert_eq!(mon_ok.observe(0xaa), Ok(true));
391 assert!(mon_ok.is_ready());
392
393 assert_eq!(mon_ok.observe(0xaa), Ok(true));
395 assert_eq!(mon_ok.observe(0xaa), Ok(true));
396 assert_eq!(mon_ok.observe(0xaa), Err(Error::EntropyHealthCheckFailed));
397 assert!(!mon_ok.is_ready());
398 assert!(mon_ok.is_failed());
399 }
400
401 #[test]
402 fn standalone_startup_test_requires_at_least_1024_samples() {
403 let short = [0u64; STARTUP_SAMPLE_COUNT - 1];
404 assert_eq!(
405 run_raw_noise_health_test(&short, 5, APT_NON_BINARY_WINDOW, 325),
406 Err(Error::DrbgInvalidRequest)
407 );
408
409 let mut varied = [0u64; STARTUP_SAMPLE_COUNT];
410 for (i, slot) in varied.iter_mut().enumerate() {
411 *slot = (i as u64) & 0xff;
412 }
413 assert_eq!(
414 run_raw_noise_health_test(&varied, 5, APT_NON_BINARY_WINDOW, 325),
415 Ok(())
416 );
417 }
418}