Skip to main content

vlo_kernel/
refold.rs

1//! Re-fold comparison (see `docs/kernel-protocol.md`). The host re-folds the last N events over the
2//! previous checkpoint and hands both hash sequences here; the first divergent seq is
3//! what it records as `nondeterminism_detected`.
4
5use vlo_types::{HashAtSeq, RefoldCheckInput, RefoldCheckOutput};
6
7fn diverged(
8    seq: u64,
9    expected: Option<&HashAtSeq>,
10    actual: Option<&HashAtSeq>,
11) -> RefoldCheckOutput {
12    RefoldCheckOutput {
13        matches: false,
14        seq: Some(seq),
15        expected: Some(expected.map(|h| h.hash.clone()).unwrap_or_default()),
16        actual: Some(actual.map(|h| h.hash.clone()).unwrap_or_default()),
17    }
18}
19
20/// Compare journaled hashes with re-folded ones and report the first divergence.
21///
22/// Both lists are read in order; a length mismatch counts as a divergence at the first
23/// seq only one side has. Never fails.
24pub fn refold_check(input: &RefoldCheckInput) -> RefoldCheckOutput {
25    let common = input.expected.len().min(input.actual.len());
26    for index in 0..common {
27        let expected = &input.expected[index];
28        let actual = &input.actual[index];
29        if expected.seq != actual.seq || expected.hash != actual.hash {
30            return diverged(expected.seq.min(actual.seq), Some(expected), Some(actual));
31        }
32    }
33    if input.expected.len() != input.actual.len() {
34        let missing_in_actual = input.expected.len() > common;
35        let present = if missing_in_actual {
36            &input.expected[common]
37        } else {
38            &input.actual[common]
39        };
40        return if missing_in_actual {
41            diverged(present.seq, Some(present), None)
42        } else {
43            diverged(present.seq, None, Some(present))
44        };
45    }
46    RefoldCheckOutput {
47        matches: true,
48        seq: None,
49        expected: None,
50        actual: None,
51    }
52}