Skip to main content

ic_memory/
physical.rs

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
7///
8/// ProtectedGenerationSlot
9///
10/// One physical generation slot that can participate in protected recovery.
11pub trait ProtectedGenerationSlot: Eq {
12    /// Generation encoded by this slot.
13    fn generation(&self) -> u64;
14
15    /// Return whether the slot passed its marker/checksum validation.
16    fn validates(&self) -> bool;
17}
18
19///
20/// DualProtectedCommitStore
21///
22/// Physical store with two protected generation slots.
23pub trait DualProtectedCommitStore {
24    /// Protected slot record type.
25    type Slot: ProtectedGenerationSlot;
26
27    /// Borrow the first physical slot.
28    fn slot0(&self) -> Option<&Self::Slot>;
29
30    /// Borrow the second physical slot.
31    fn slot1(&self) -> Option<&Self::Slot>;
32
33    /// Return true when no commit slot has ever been written.
34    fn is_uninitialized(&self) -> bool {
35        self.slot0().is_none() && self.slot1().is_none()
36    }
37
38    /// Return the highest-generation valid physical slot.
39    fn authoritative_slot(&self) -> Result<AuthoritativeSlot<'_, Self::Slot>, CommitRecoveryError> {
40        select_authoritative_slot(self.slot0(), self.slot1())
41    }
42
43    /// Return the slot that should receive the next staged generation write.
44    ///
45    /// The result is derived from validated recovery state. It does not trust a
46    /// separate current-pointer/header field.
47    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///
56/// CommitSlotIndex
57///
58/// Physical dual-slot index selected by protected recovery.
59#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
60pub enum CommitSlotIndex {
61    /// First physical commit slot.
62    Slot0,
63    /// Second physical commit slot.
64    Slot1,
65}
66
67impl CommitSlotIndex {
68    /// Return the opposite physical slot.
69    #[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///
79/// AuthoritativeSlot
80///
81/// Highest-generation valid slot selected by protected recovery.
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub struct AuthoritativeSlot<'slot, T> {
84    /// Physical slot index.
85    pub index: CommitSlotIndex,
86    /// Valid committed generation in that slot.
87    pub record: &'slot T,
88}
89
90/// Select the highest-generation valid physical slot.
91pub 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///
127/// CommittedGenerationBytes
128///
129/// Physically committed ledger generation payload protected by a checksum.
130#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
131pub struct CommittedGenerationBytes {
132    /// Generation number represented by this payload.
133    pub generation: u64,
134    /// Physical commit marker. Readers reject records with an invalid marker.
135    pub commit_marker: u64,
136    /// Checksum over the generation, marker, and payload bytes.
137    pub checksum: u64,
138    /// Encoded ledger generation payload.
139    pub payload: Vec<u8>,
140}
141
142impl CommittedGenerationBytes {
143    /// Build a committed generation record.
144    #[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    /// Return whether the marker and checksum validate.
157    #[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///
174/// DualCommitStore
175///
176/// Dual-slot protected commit protocol for encoded ledger generations.
177///
178/// Writers stage a complete generation record into the inactive slot. Readers
179/// recover by selecting the highest-generation valid slot. A torn or partial
180/// write cannot become authoritative unless its marker and checksum validate.
181///
182/// The checksum is for torn-write and accidental-corruption detection only. It
183/// is not a cryptographic hash and does not provide adversarial tamper
184/// resistance.
185#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
186pub struct DualCommitStore {
187    /// First physical commit slot.
188    pub slot0: Option<CommittedGenerationBytes>,
189    /// Second physical commit slot.
190    pub slot1: Option<CommittedGenerationBytes>,
191}
192
193impl DualCommitStore {
194    /// Return true when no commit slot has ever been written.
195    #[must_use]
196    pub const fn is_uninitialized(&self) -> bool {
197        self.slot0.is_none() && self.slot1.is_none()
198    }
199
200    /// Return the highest-generation valid committed record.
201    pub fn authoritative(&self) -> Result<&CommittedGenerationBytes, CommitRecoveryError> {
202        self.authoritative_slot()
203            .map(|authoritative| authoritative.record)
204    }
205
206    /// Build a read-only recovery diagnostic for the protected commit slots.
207    #[must_use]
208    pub fn diagnostic(&self) -> CommitStoreDiagnostic {
209        CommitStoreDiagnostic::from_store(self)
210    }
211
212    /// Commit a new payload to the inactive slot.
213    ///
214    /// The returned store models the post-write physical state. If a real
215    /// substrate traps before the inactive slot is fully written, the prior
216    /// valid slot remains authoritative under `authoritative`.
217    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    /// Commit `payload` as an explicitly numbered physical generation.
236    ///
237    /// This is the preferred API for logical ledger commits: the physical slot
238    /// generation is taken from the logical ledger generation and checked
239    /// against the recovered physical predecessor.
240    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    /// Simulate a torn write into the inactive slot.
275    ///
276    /// This helper is intentionally part of the model because recovery behavior
277    /// is an ABI requirement, not an implementation detail.
278    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///
303/// CommitStoreDiagnostic
304///
305/// Read-only diagnostic summary of protected commit recovery state.
306#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
307pub struct CommitStoreDiagnostic {
308    /// First physical commit slot diagnostic.
309    pub slot0: CommitSlotDiagnostic,
310    /// Second physical commit slot diagnostic.
311    pub slot1: CommitSlotDiagnostic,
312    /// Highest valid generation selected by recovery.
313    pub authoritative_generation: Option<u64>,
314    /// Recovery error when no authoritative generation can be selected.
315    pub recovery_error: Option<CommitRecoveryError>,
316}
317
318impl CommitStoreDiagnostic {
319    /// Build a read-only recovery diagnostic from a dual protected commit store.
320    #[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///
336/// CommitSlotDiagnostic
337///
338/// Read-only diagnostic summary for one protected commit slot.
339#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
340pub struct CommitSlotDiagnostic {
341    /// Whether a physical slot record is present.
342    pub present: bool,
343    /// Generation encoded by the slot, if present.
344    pub generation: Option<u64>,
345    /// Whether marker and checksum validation succeeded.
346    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///
367/// CommitRecoveryError
368///
369/// Protected commit recovery failure.
370#[derive(Clone, Copy, Debug, Deserialize, Eq, thiserror::Error, PartialEq, Serialize)]
371pub enum CommitRecoveryError {
372    /// No committed slot passed marker and checksum validation.
373    #[error("no valid committed ledger generation")]
374    NoValidGeneration,
375    /// Both physical slots validated at the same generation but contained different bytes.
376    #[error("ambiguous committed ledger generation {generation}")]
377    AmbiguousGeneration {
378        /// Ambiguous physical generation.
379        generation: u64,
380    },
381    /// Physical generation advancement would overflow.
382    #[error("committed ledger generation {generation} cannot be advanced without overflow")]
383    GenerationOverflow {
384        /// Last valid physical generation.
385        generation: u64,
386    },
387    /// Caller attempted to commit a physical generation other than the next generation.
388    #[error("expected committed ledger generation {expected}, got {actual}")]
389    UnexpectedGeneration {
390        /// Expected next physical generation.
391        expected: u64,
392        /// Actual requested physical generation.
393        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}