Skip to main content

ratify_protocol/v2/reference/
journal.rs

1//! The reference anchored `SecurityJournalV2` store. Mirrors Go
2//! `v2reference/journal.go`.
3
4use std::sync::{Mutex, MutexGuard};
5
6use crate::v2::context::V2Context;
7use crate::v2::errors::V2Result;
8use crate::v2::journal::{
9    empty_security_journal_v2, validate_security_journal_transition_inner, SecurityJournalHeadV2,
10    SecurityJournalStoreErrorV2, SecurityJournalStoreV2, SecurityJournalV2,
11};
12use crate::v2::journal_snapshot::{
13    export_security_journal_snapshot_v2, import_security_journal_snapshot_v2,
14};
15
16struct Anchored {
17    head: SecurityJournalHeadV2,
18    snapshot: Vec<u8>,
19}
20
21/// The reference anchored `SecurityJournalV2` store. It persists the
22/// canonical snapshot bytes and an anchored head, and advances both under one
23/// lock by compare-and-swap. TEST/REFERENCE ONLY: an in-process anchor is not
24/// an independent, rollback-resistant head.
25pub struct JournalStore {
26    state: Mutex<Anchored>,
27}
28
29impl std::fmt::Debug for JournalStore {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("JournalStore")
32            .field("head", &self.head())
33            .finish()
34    }
35}
36
37impl JournalStore {
38    /// A store anchored at the genesis journal.
39    pub fn new() -> V2Result<Self> {
40        let genesis = empty_security_journal_v2();
41        let snapshot = export_security_journal_snapshot_v2(&genesis)?;
42        Ok(JournalStore {
43            state: Mutex::new(Anchored {
44                head: SecurityJournalHeadV2 {
45                    generation: genesis.generation,
46                    digest: genesis.digest,
47                },
48                snapshot,
49            }),
50        })
51    }
52
53    fn lock(&self) -> MutexGuard<'_, Anchored> {
54        // A panic while holding the lock never leaves a half-written state:
55        // head and snapshot are replaced together after every check passed.
56        self.state
57            .lock()
58            .unwrap_or_else(|poisoned| poisoned.into_inner())
59    }
60
61    /// The anchored head.
62    pub fn head(&self) -> SecurityJournalHeadV2 {
63        self.lock().head.clone()
64    }
65
66    /// The anchored head and stored snapshot bytes (read by the
67    /// single-device profile's complete-state digest).
68    pub(crate) fn anchored(&self) -> (SecurityJournalHeadV2, Vec<u8>) {
69        let state = self.lock();
70        (state.head.clone(), state.snapshot.clone())
71    }
72
73    /// A store holding exactly `head` and `snapshot` (a copy of another
74    /// store's anchored state).
75    pub(crate) fn from_anchored(head: SecurityJournalHeadV2, snapshot: Vec<u8>) -> Self {
76        JournalStore {
77            state: Mutex::new(Anchored { head, snapshot }),
78        }
79    }
80
81    /// Put back a previously read anchored state (undo of a refused change).
82    pub(crate) fn restore_anchored(&self, head: SecurityJournalHeadV2, snapshot: Vec<u8>) {
83        let mut state = self.lock();
84        state.head = head;
85        state.snapshot = snapshot;
86    }
87}
88
89impl SecurityJournalStoreV2 for JournalStore {
90    /// Imports the stored snapshot against the anchored head.
91    fn load(&self, _ctx: &V2Context) -> V2Result<(SecurityJournalV2, SecurityJournalHeadV2)> {
92        let state = self.lock();
93        let journal = import_security_journal_snapshot_v2(&state.snapshot, &state.head)?;
94        Ok((journal, state.head.clone()))
95    }
96
97    fn compare_and_swap(
98        &self,
99        _ctx: &V2Context,
100        expected: &SecurityJournalHeadV2,
101        next: &SecurityJournalV2,
102    ) -> Result<(), SecurityJournalStoreErrorV2> {
103        let mut state = self.lock();
104        if *expected != state.head {
105            return Err(SecurityJournalStoreErrorV2::Conflict);
106        }
107        let current = import_security_journal_snapshot_v2(&state.snapshot, &state.head)?;
108        validate_security_journal_transition_inner(&current, next)?;
109        let snapshot = export_security_journal_snapshot_v2(next)?;
110        state.snapshot = snapshot;
111        state.head = SecurityJournalHeadV2 {
112            generation: next.generation,
113            digest: next.digest.clone(),
114        };
115        Ok(())
116    }
117}