1use serde::{Deserialize, Serialize};
2
3const COMMIT_MARKER: u64 = 0x4943_4D45_4D43_4F4D;
4const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
5const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
6
7pub trait ProtectedGenerationSlot: Eq {
12 fn generation(&self) -> u64;
14
15 fn validates(&self) -> bool;
17}
18
19pub trait DualProtectedCommitStore {
24 type Slot: ProtectedGenerationSlot;
26
27 fn slot0(&self) -> Option<&Self::Slot>;
29
30 fn slot1(&self) -> Option<&Self::Slot>;
32
33 fn is_uninitialized(&self) -> bool {
35 self.slot0().is_none() && self.slot1().is_none()
36 }
37
38 fn authoritative_slot(&self) -> Result<AuthoritativeSlot<'_, Self::Slot>, CommitRecoveryError> {
40 select_authoritative_slot(self.slot0(), self.slot1())
41 }
42
43 fn inactive_slot_index(&self) -> CommitSlotIndex {
48 match self.authoritative_slot() {
49 Ok(authoritative) => authoritative.index.opposite(),
50 Err(_) => CommitSlotIndex::Slot0,
51 }
52 }
53}
54
55#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
60pub enum CommitSlotIndex {
61 Slot0,
63 Slot1,
65}
66
67impl CommitSlotIndex {
68 #[must_use]
70 pub const fn opposite(self) -> Self {
71 match self {
72 Self::Slot0 => Self::Slot1,
73 Self::Slot1 => Self::Slot0,
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub struct AuthoritativeSlot<'slot, T> {
84 pub index: CommitSlotIndex,
86 pub record: &'slot T,
88}
89
90pub fn select_authoritative_slot<'slot, T: ProtectedGenerationSlot>(
92 slot0: Option<&'slot T>,
93 slot1: Option<&'slot T>,
94) -> Result<AuthoritativeSlot<'slot, T>, CommitRecoveryError> {
95 let slot0 = slot0
96 .filter(|slot| slot.validates())
97 .map(|record| AuthoritativeSlot {
98 index: CommitSlotIndex::Slot0,
99 record,
100 });
101 let slot1 = slot1
102 .filter(|slot| slot.validates())
103 .map(|record| AuthoritativeSlot {
104 index: CommitSlotIndex::Slot1,
105 record,
106 });
107
108 match (slot0, slot1) {
109 (Some(left), Some(right))
110 if left.record.generation() == right.record.generation()
111 && left.record != right.record =>
112 {
113 Err(CommitRecoveryError::AmbiguousGeneration {
114 generation: left.record.generation(),
115 })
116 }
117 (Some(left), Some(right)) if right.record.generation() > left.record.generation() => {
118 Ok(right)
119 }
120 (Some(left), Some(_) | None) => Ok(left),
121 (None, Some(right)) => Ok(right),
122 (None, None) => Err(CommitRecoveryError::NoValidGeneration),
123 }
124}
125
126#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
131pub struct CommittedGenerationBytes {
132 pub generation: u64,
134 pub commit_marker: u64,
136 pub checksum: u64,
138 pub payload: Vec<u8>,
140}
141
142impl CommittedGenerationBytes {
143 #[must_use]
145 pub fn new(generation: u64, payload: Vec<u8>) -> Self {
146 let mut record = Self {
147 generation,
148 commit_marker: COMMIT_MARKER,
149 checksum: 0,
150 payload,
151 };
152 record.checksum = generation_checksum(&record);
153 record
154 }
155
156 #[must_use]
158 pub fn validates(&self) -> bool {
159 self.commit_marker == COMMIT_MARKER && self.checksum == generation_checksum(self)
160 }
161}
162
163impl ProtectedGenerationSlot for CommittedGenerationBytes {
164 fn generation(&self) -> u64 {
165 self.generation
166 }
167
168 fn validates(&self) -> bool {
169 self.validates()
170 }
171}
172
173#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
186pub struct DualCommitStore {
187 pub slot0: Option<CommittedGenerationBytes>,
189 pub slot1: Option<CommittedGenerationBytes>,
191}
192
193impl DualCommitStore {
194 #[must_use]
196 pub const fn is_uninitialized(&self) -> bool {
197 self.slot0.is_none() && self.slot1.is_none()
198 }
199
200 pub fn authoritative(&self) -> Result<&CommittedGenerationBytes, CommitRecoveryError> {
202 self.authoritative_slot()
203 .map(|authoritative| authoritative.record)
204 }
205
206 #[must_use]
208 pub fn diagnostic(&self) -> CommitStoreDiagnostic {
209 CommitStoreDiagnostic::from_store(self)
210 }
211
212 pub fn commit_payload(
218 &mut self,
219 payload: Vec<u8>,
220 ) -> Result<&CommittedGenerationBytes, CommitRecoveryError> {
221 let next_generation =
222 match self.authoritative() {
223 Ok(record) => record.generation.checked_add(1).ok_or(
224 CommitRecoveryError::GenerationOverflow {
225 generation: record.generation,
226 },
227 )?,
228 Err(CommitRecoveryError::NoValidGeneration) if self.is_uninitialized() => 0,
229 Err(err) => return Err(err),
230 };
231
232 self.commit_payload_at_generation(next_generation, payload)
233 }
234
235 pub fn commit_payload_at_generation(
241 &mut self,
242 generation: u64,
243 payload: Vec<u8>,
244 ) -> Result<&CommittedGenerationBytes, CommitRecoveryError> {
245 match self.authoritative() {
246 Ok(record) => {
247 let expected = record.generation.checked_add(1).ok_or(
248 CommitRecoveryError::GenerationOverflow {
249 generation: record.generation,
250 },
251 )?;
252 if generation != expected {
253 return Err(CommitRecoveryError::UnexpectedGeneration {
254 expected,
255 actual: generation,
256 });
257 }
258 }
259 Err(CommitRecoveryError::NoValidGeneration) if self.is_uninitialized() => {}
260 Err(err) => return Err(err),
261 }
262
263 let next = CommittedGenerationBytes::new(generation, payload);
264
265 if self.inactive_slot_index() == CommitSlotIndex::Slot0 {
266 self.slot0 = Some(next);
267 } else {
268 self.slot1 = Some(next);
269 }
270
271 self.authoritative()
272 }
273
274 pub fn write_corrupt_inactive_slot(&mut self, generation: u64, payload: Vec<u8>) {
279 let mut corrupt = CommittedGenerationBytes::new(generation, payload);
280 corrupt.checksum = corrupt.checksum.wrapping_add(1);
281
282 if self.inactive_slot_index() == CommitSlotIndex::Slot0 {
283 self.slot0 = Some(corrupt);
284 } else {
285 self.slot1 = Some(corrupt);
286 }
287 }
288}
289
290impl DualProtectedCommitStore for DualCommitStore {
291 type Slot = CommittedGenerationBytes;
292
293 fn slot0(&self) -> Option<&Self::Slot> {
294 self.slot0.as_ref()
295 }
296
297 fn slot1(&self) -> Option<&Self::Slot> {
298 self.slot1.as_ref()
299 }
300}
301
302#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
307pub struct CommitStoreDiagnostic {
308 pub slot0: CommitSlotDiagnostic,
310 pub slot1: CommitSlotDiagnostic,
312 pub authoritative_generation: Option<u64>,
314 pub recovery_error: Option<CommitRecoveryError>,
316}
317
318impl CommitStoreDiagnostic {
319 #[must_use]
321 pub fn from_store<S: DualProtectedCommitStore>(store: &S) -> Self {
322 let (authoritative_generation, recovery_error) = match store.authoritative_slot() {
323 Ok(slot) => (Some(slot.record.generation()), None),
324 Err(err) => (None, Some(err)),
325 };
326 Self {
327 slot0: CommitSlotDiagnostic::from_slot(store.slot0()),
328 slot1: CommitSlotDiagnostic::from_slot(store.slot1()),
329 authoritative_generation,
330 recovery_error,
331 }
332 }
333}
334
335#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
340pub struct CommitSlotDiagnostic {
341 pub present: bool,
343 pub generation: Option<u64>,
345 pub valid: bool,
347}
348
349impl CommitSlotDiagnostic {
350 fn from_slot<T: ProtectedGenerationSlot>(slot: Option<&T>) -> Self {
351 match slot {
352 Some(record) => Self {
353 present: true,
354 generation: Some(record.generation()),
355 valid: record.validates(),
356 },
357 None => Self {
358 present: false,
359 generation: None,
360 valid: false,
361 },
362 }
363 }
364}
365
366#[derive(Clone, Copy, Debug, Deserialize, Eq, thiserror::Error, PartialEq, Serialize)]
371pub enum CommitRecoveryError {
372 #[error("no valid committed ledger generation")]
374 NoValidGeneration,
375 #[error("ambiguous committed ledger generation {generation}")]
377 AmbiguousGeneration {
378 generation: u64,
380 },
381 #[error("committed ledger generation {generation} cannot be advanced without overflow")]
383 GenerationOverflow {
384 generation: u64,
386 },
387 #[error("expected committed ledger generation {expected}, got {actual}")]
389 UnexpectedGeneration {
390 expected: u64,
392 actual: u64,
394 },
395}
396
397fn generation_checksum(generation: &CommittedGenerationBytes) -> u64 {
398 let mut hash = FNV_OFFSET;
399 hash = hash_u64(hash, generation.generation);
400 hash = hash_u64(hash, generation.commit_marker);
401 hash = hash_usize(hash, generation.payload.len());
402 for byte in &generation.payload {
403 hash = hash_byte(hash, *byte);
404 }
405 hash
406}
407
408fn hash_usize(hash: u64, value: usize) -> u64 {
409 hash_u64(hash, value as u64)
410}
411
412fn hash_u64(mut hash: u64, value: u64) -> u64 {
413 for byte in value.to_le_bytes() {
414 hash = hash_byte(hash, byte);
415 }
416 hash
417}
418
419const fn hash_byte(hash: u64, byte: u8) -> u64 {
420 (hash ^ byte as u64).wrapping_mul(FNV_PRIME)
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 fn payload(value: u8) -> Vec<u8> {
428 vec![value; 4]
429 }
430
431 #[test]
432 fn committed_generation_validates_marker_and_checksum() {
433 let mut generation = CommittedGenerationBytes::new(7, payload(1));
434 assert!(generation.validates());
435
436 generation.checksum = generation.checksum.wrapping_add(1);
437 assert!(!generation.validates());
438 }
439
440 #[test]
441 fn authoritative_selects_highest_valid_generation() {
442 let mut store = DualCommitStore::default();
443 store.commit_payload(payload(1)).expect("first commit");
444 store.commit_payload(payload(2)).expect("second commit");
445
446 let authoritative = store.authoritative().expect("authoritative");
447 let authoritative_slot =
448 select_authoritative_slot(store.slot0.as_ref(), store.slot1.as_ref())
449 .expect("authoritative slot");
450
451 assert_eq!(authoritative.generation, 1);
452 assert_eq!(authoritative.payload, payload(2));
453 assert_eq!(authoritative_slot.index, CommitSlotIndex::Slot1);
454 assert_eq!(authoritative_slot.record.payload, payload(2));
455 }
456
457 #[test]
458 fn corrupt_newer_slot_leaves_prior_generation_authoritative() {
459 let mut store = DualCommitStore::default();
460 store.commit_payload(payload(1)).expect("first commit");
461 store.write_corrupt_inactive_slot(1, payload(2));
462
463 let authoritative = store.authoritative().expect("authoritative");
464
465 assert_eq!(authoritative.generation, 0);
466 assert_eq!(authoritative.payload, payload(1));
467 }
468
469 #[test]
470 fn no_valid_generation_fails_closed() {
471 let mut store = DualCommitStore::default();
472 store.write_corrupt_inactive_slot(0, payload(1));
473 store.write_corrupt_inactive_slot(1, payload(2));
474
475 let err = store.authoritative().expect_err("no valid slot");
476
477 assert_eq!(err, CommitRecoveryError::NoValidGeneration);
478 }
479
480 #[test]
481 fn same_generation_identical_slots_recover_deterministically() {
482 let committed = CommittedGenerationBytes::new(7, payload(1));
483 let store = DualCommitStore {
484 slot0: Some(committed.clone()),
485 slot1: Some(committed),
486 };
487
488 let authoritative = store.authoritative_slot().expect("authoritative");
489
490 assert_eq!(authoritative.index, CommitSlotIndex::Slot0);
491 assert_eq!(authoritative.record.generation, 7);
492 }
493
494 #[test]
495 fn same_generation_divergent_slots_fail_closed() {
496 let store = DualCommitStore {
497 slot0: Some(CommittedGenerationBytes::new(7, payload(1))),
498 slot1: Some(CommittedGenerationBytes::new(7, payload(2))),
499 };
500
501 let err = store.authoritative().expect_err("ambiguous generation");
502
503 assert_eq!(
504 err,
505 CommitRecoveryError::AmbiguousGeneration { generation: 7 }
506 );
507 }
508
509 #[test]
510 fn physical_generation_overflow_fails_closed() {
511 let mut store = DualCommitStore {
512 slot0: Some(CommittedGenerationBytes::new(u64::MAX, payload(1))),
513 slot1: None,
514 };
515
516 let err = store
517 .commit_payload(payload(2))
518 .expect_err("overflow must fail");
519
520 assert_eq!(
521 err,
522 CommitRecoveryError::GenerationOverflow {
523 generation: u64::MAX
524 }
525 );
526 }
527
528 #[test]
529 fn diagnostic_reports_authoritative_generation_and_corrupt_slots() {
530 let mut store = DualCommitStore::default();
531 store.commit_payload(payload(1)).expect("first commit");
532 store.write_corrupt_inactive_slot(1, payload(2));
533
534 let diagnostic = store.diagnostic();
535
536 assert_eq!(diagnostic.authoritative_generation, Some(0));
537 assert_eq!(diagnostic.recovery_error, None);
538 assert_eq!(diagnostic.slot0.generation, Some(0));
539 assert!(diagnostic.slot0.valid);
540 assert_eq!(diagnostic.slot1.generation, Some(1));
541 assert!(!diagnostic.slot1.valid);
542 }
543
544 #[test]
545 fn diagnostic_reports_no_valid_generation_for_empty_store() {
546 let diagnostic = DualCommitStore::default().diagnostic();
547
548 assert_eq!(diagnostic.authoritative_generation, None);
549 assert_eq!(
550 diagnostic.recovery_error,
551 Some(CommitRecoveryError::NoValidGeneration)
552 );
553 assert!(!diagnostic.slot0.present);
554 assert!(!diagnostic.slot1.present);
555 }
556
557 #[test]
558 fn diagnostic_builds_from_any_dual_protected_store() {
559 #[derive(Eq, PartialEq)]
560 struct TestSlot {
561 generation: u64,
562 valid: bool,
563 }
564
565 impl ProtectedGenerationSlot for TestSlot {
566 fn generation(&self) -> u64 {
567 self.generation
568 }
569
570 fn validates(&self) -> bool {
571 self.valid
572 }
573 }
574
575 struct TestStore {
576 slot0: Option<TestSlot>,
577 slot1: Option<TestSlot>,
578 }
579
580 impl DualProtectedCommitStore for TestStore {
581 type Slot = TestSlot;
582
583 fn slot0(&self) -> Option<&Self::Slot> {
584 self.slot0.as_ref()
585 }
586
587 fn slot1(&self) -> Option<&Self::Slot> {
588 self.slot1.as_ref()
589 }
590 }
591
592 let diagnostic = CommitStoreDiagnostic::from_store(&TestStore {
593 slot0: Some(TestSlot {
594 generation: 8,
595 valid: true,
596 }),
597 slot1: Some(TestSlot {
598 generation: 9,
599 valid: false,
600 }),
601 });
602
603 assert_eq!(diagnostic.authoritative_generation, Some(8));
604 assert!(diagnostic.slot0.valid);
605 assert_eq!(diagnostic.slot1.generation, Some(9));
606 assert!(!diagnostic.slot1.valid);
607 }
608
609 #[test]
610 fn uninitialized_distinguishes_empty_from_corrupt() {
611 let mut store = DualCommitStore::default();
612 assert!(store.is_uninitialized());
613
614 store.write_corrupt_inactive_slot(0, payload(1));
615
616 assert!(!store.is_uninitialized());
617 }
618
619 #[test]
620 fn commit_after_corrupt_slot_advances_from_prior_valid_generation() {
621 let mut store = DualCommitStore::default();
622 store.commit_payload(payload(1)).expect("first commit");
623 store.write_corrupt_inactive_slot(1, payload(2));
624 store.commit_payload(payload(3)).expect("third commit");
625
626 let authoritative = store.authoritative().expect("authoritative");
627
628 assert_eq!(authoritative.generation, 1);
629 assert_eq!(authoritative.payload, payload(3));
630 }
631}