Skip to main content

gent_daemon/store/handoff/
journal.rs

1//! Transfer of decision history precedes successor signing and activation.
2use super::*;
3use gent_crypto::succession::journal::{MAX_BYTES, MAX_MANIFEST_BYTES, Manifest, PAGE_BYTES};
4
5const MAX_RESERVED_BYTES: usize = 2 * MAX_BYTES;
6const MAX_SNAPSHOTS: usize = LIMIT + 1;
7
8pub(super) fn schema(db: &Connection, previous: i64) -> Result<()> {
9    let count: usize = db.query_row("SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name IN ('owner_journals','owner_journal_pages')", [], |r| r.get(0))?;
10    if previous < 19 && count == 0 {
11        db.execute_batch("CREATE TABLE owner_journals(id TEXT PRIMARY KEY CHECK(length(id)=36),source INTEGER NOT NULL CHECK(source IN (0,1)),manifest BLOB NOT NULL CHECK(length(manifest)<=131072),authorization BLOB NOT NULL CHECK(length(authorization)<=4096),bytes INTEGER NOT NULL CHECK(bytes>0 AND bytes<=83886080));
12        CREATE TABLE owner_journal_pages(id TEXT NOT NULL REFERENCES owner_journals(id),page INTEGER NOT NULL CHECK(page>=0 AND page<320),body BLOB NOT NULL CHECK(length(body)>0 AND length(body)<=262144),PRIMARY KEY(id,page));")?;
13    } else {
14        ensure!(count == 2, "owner decision transfer journal is missing");
15        db.prepare("SELECT id,source,manifest,authorization,bytes FROM owner_journals LIMIT 0")?;
16        db.prepare("SELECT id,page,body FROM owner_journal_pages LIMIT 0")?;
17    }
18    Ok(())
19}
20
21pub(super) fn usage(db: &Connection) -> Result<Value> {
22    let (count, bytes): (usize, usize) = db.query_row(
23        "SELECT COUNT(*),COALESCE(SUM(bytes),0) FROM owner_journals",
24        [],
25        |r| Ok((r.get(0)?, r.get(1)?)),
26    )?;
27    ensure!(
28        count <= MAX_SNAPSHOTS && bytes <= MAX_RESERVED_BYTES,
29        "owner journal transfer budget exceeded"
30    );
31    Ok(json!({"snapshots":count,"reserved_bytes":bytes,"max_reserved_bytes":MAX_RESERVED_BYTES}))
32}
33
34pub(crate) fn load(
35    db: &Connection,
36    id: &str,
37    source: bool,
38) -> Result<(Manifest, SignedOwnerTransition)> {
39    let (wire, auth, bytes): (Vec<u8>, Vec<u8>, usize) = db.query_row(
40        "SELECT manifest,authorization,bytes FROM owner_journals WHERE id=?1 AND source=?2",
41        params![id, source],
42        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
43    )?;
44    ensure!(
45        wire.len() <= MAX_MANIFEST_BYTES,
46        "owner journal manifest exceeds limit"
47    );
48    let manifest = Manifest::decode(&wire)?;
49    ensure!(manifest.bytes == bytes, "owner journal reservation changed");
50    Ok((manifest, SignedOwnerTransition::decode(&auth)?))
51}
52
53fn reserve(
54    db: &Connection,
55    candidate: &SignedOwnerCandidate,
56    source: bool,
57    authorization: &SignedOwnerTransition,
58    manifest: &Manifest,
59) -> Result<()> {
60    let prior: bool = db.query_row(
61        "SELECT EXISTS(SELECT 1 FROM owner_journals WHERE id=?1)",
62        [&candidate.candidate.id],
63        |r| r.get(0),
64    )?;
65    if prior {
66        let (saved, auth) = load(db, &candidate.candidate.id, source)?;
67        ensure!(
68            saved == *manifest && auth == *authorization,
69            "owner journal request changed"
70        );
71        return Ok(());
72    }
73    let (count, bytes): (usize, usize) = db.query_row(
74        "SELECT COUNT(*),COALESCE(SUM(bytes),0) FROM owner_journals",
75        [],
76        |r| Ok((r.get(0)?, r.get(1)?)),
77    )?;
78    ensure!(
79        count < MAX_SNAPSHOTS
80            && bytes
81                .checked_add(manifest.bytes)
82                .is_some_and(|n| n <= MAX_RESERVED_BYTES),
83        "owner journal transfer budget exhausted"
84    );
85    db.execute(
86        "INSERT INTO owner_journals VALUES(?1,?2,?3,?4,?5)",
87        params![
88            candidate.candidate.id,
89            source,
90            manifest.encode()?,
91            authorization.encode()?,
92            manifest.bytes
93        ],
94    )?;
95    Ok(())
96}
97
98pub(super) fn capture(
99    db: &Connection,
100    state: &VerifiedState,
101    candidate: &SignedOwnerCandidate,
102) -> Result<(Manifest, Vec<u8>)> {
103    let (count, body) = configuration::storage::handoff::snapshot(db, state.checkpoint())?;
104    configuration::storage::handoff::verify_snapshot(db, state.checkpoint(), count, &body)?;
105    let manifest = Manifest::new(candidate, count, &body)?;
106    Ok((manifest, body))
107}
108
109pub(super) fn save_source(
110    db: &Connection,
111    candidate: &SignedOwnerCandidate,
112    authorization: &SignedOwnerTransition,
113    manifest: &Manifest,
114    body: &[u8],
115) -> Result<()> {
116    reserve(db, candidate, true, authorization, manifest)?;
117    for (page, body) in body.chunks(PAGE_BYTES).enumerate() {
118        manifest.verify_page(page, body)?;
119        db.execute(
120            "INSERT INTO owner_journal_pages VALUES(?1,?2,?3)",
121            params![candidate.candidate.id, page, body],
122        )?;
123    }
124    Ok(())
125}
126
127pub(super) fn check_source(
128    db: &Connection,
129    state: &VerifiedState,
130    candidate: &SignedOwnerCandidate,
131    authorization: &SignedOwnerTransition,
132) -> Result<()> {
133    if authorization
134        .transition
135        .successor
136        .as_ref()
137        .is_some_and(|s| s.journal.is_some())
138    {
139        let (manifest, auth) = load(db, &candidate.candidate.id, true)?;
140        ensure!(
141            auth == *authorization,
142            "owner decision journal authorization changed"
143        );
144        manifest.verify(state, candidate, authorization)?;
145    }
146    Ok(())
147}
148
149pub(crate) fn candidate(
150    db: &Connection,
151    id: &str,
152) -> Result<(VerifiedState, SignedOwnerCandidate)> {
153    let (baseline, candidate): (Vec<u8>, Vec<u8>) = db.query_row(
154        "SELECT baseline,candidate FROM owner_candidates WHERE id=?1",
155        [id],
156        |r| Ok((r.get(0)?, r.get(1)?)),
157    )?;
158    let candidate = SignedOwnerCandidate::decode(&candidate)?;
159    ensure!(
160        candidate.candidate.id == id,
161        "owner journal candidate identity changed"
162    );
163    let baseline = restore(&candidate, &baseline)?;
164    Ok((baseline, candidate))
165}
166
167fn incoming(
168    db: &Connection,
169    id: &str,
170) -> Result<(
171    VerifiedState,
172    SignedOwnerCandidate,
173    Manifest,
174    SignedOwnerTransition,
175)> {
176    let (baseline, candidate) = candidate(db, id)?;
177    let (manifest, authorization) = load(db, id, false)?;
178    manifest.verify(&baseline, &candidate, &authorization)?;
179    Ok((baseline, candidate, manifest, authorization))
180}
181
182pub(crate) fn page(
183    db: &Connection,
184    id: &str,
185    manifest: &Manifest,
186    index: usize,
187) -> Result<Vec<u8>> {
188    ensure!(
189        index < manifest.pages.len(),
190        "owner journal page outside manifest"
191    );
192    let body: Vec<u8> = db.query_row(
193        "SELECT body FROM owner_journal_pages WHERE id=?1 AND page=?2",
194        params![id, index],
195        |r| r.get(0),
196    )?;
197    manifest.verify_page(index, &body)?;
198    Ok(body)
199}
200
201fn progress(db: &Connection, id: &str, manifest: &Manifest) -> Result<Value> {
202    let indices = db
203        .prepare("SELECT page FROM owner_journal_pages WHERE id=?1 ORDER BY page")?
204        .query_map([id], |r| r.get::<_, usize>(0))?
205        .collect::<rusqlite::Result<Vec<_>>>()?;
206    ensure!(
207        indices.len() <= manifest.pages.len() && indices.iter().all(|i| *i < manifest.pages.len()),
208        "owner journal page inventory changed"
209    );
210    let missing: Vec<usize> = (0..manifest.pages.len())
211        .filter(|i| indices.binary_search(i).is_err())
212        .collect();
213    let activated: bool = db.query_row(
214        "SELECT EXISTS(SELECT 1 FROM owner_epochs WHERE local_candidate=?1)",
215        [id],
216        |r| r.get(0),
217    )?;
218    Ok(
219        json!({"request_id":id,"pages":manifest.pages.len(),"received":indices.len(),
220        "missing":missing,"pages_complete":missing.is_empty(),"entries":manifest.entries,"bytes":manifest.bytes,"activated":activated}),
221    )
222}
223
224pub(super) fn require_complete(
225    db: &Connection,
226    baseline: &VerifiedState,
227    candidate: &SignedOwnerCandidate,
228    authorization: &SignedOwnerTransition,
229) -> Result<(usize, Vec<u8>)> {
230    let (manifest, saved) = load(db, &candidate.candidate.id, false)?;
231    ensure!(
232        saved == *authorization,
233        "owner journal authorization changed"
234    );
235    manifest.verify(baseline, candidate, authorization)?;
236    ensure!(
237        progress(db, &candidate.candidate.id, &manifest)?["pages_complete"] == true,
238        "owner decision journal transfer is incomplete"
239    );
240    let mut body = Vec::with_capacity(manifest.bytes);
241    for index in 0..manifest.pages.len() {
242        body.extend(page(db, &candidate.candidate.id, &manifest, index)?);
243    }
244    configuration::storage::handoff::verify_snapshot(
245        db,
246        baseline.checkpoint(),
247        manifest.entries,
248        &body,
249    )?;
250    Ok((manifest.entries, body))
251}
252
253/// A later checkpoint admits only exact, already imported artifacts for a
254/// locally activated transition in the accepted chain. It cannot start or
255/// repair an import after authority has moved on.
256fn check_destination(
257    db: &Connection,
258    state: &VerifiedState,
259    node: &gent_crypto::NodeIdentity,
260    baseline: &VerifiedState,
261    candidate: &SignedOwnerCandidate,
262    authorization: &SignedOwnerTransition,
263) -> Result<bool> {
264    ensure!(
265        candidate.candidate.node.id == node.id()
266            && candidate.candidate.node.signing_key == node.public_key()
267            && baseline.anchor() == state.anchor(),
268        "owner journal belongs to another node or cluster"
269    );
270    if baseline.checkpoint() == state.checkpoint() {
271        return Ok(false);
272    }
273    ensure!(
274        state
275            .state()
276            .owner_transitions
277            .get(baseline.owner_epoch() as usize)
278            == Some(authorization),
279        "owner journal local authority changed"
280    );
281    let local: Option<String> = db.query_row(
282        "SELECT local_candidate FROM owner_epochs WHERE epoch=?1",
283        [authorization.transition.epoch],
284        |r| r.get(0),
285    )?;
286    ensure!(
287        local.as_deref() == Some(&candidate.candidate.id),
288        "owner journal was not locally activated"
289    );
290    Ok(true)
291}
292
293/// Caller must hold the receive/write transaction. No owner authority is
294/// installed here; signatures authorize only this candidate's journal import.
295pub(crate) fn begin_import(
296    db: &Connection,
297    state: &VerifiedState,
298    node: &gent_crypto::NodeIdentity,
299    id: &str,
300    authorization: &SignedOwnerTransition,
301    manifest: &Manifest,
302) -> Result<Value> {
303    let (baseline, candidate) = candidate(db, id)?;
304    manifest.verify(&baseline, &candidate, authorization)?;
305    if check_destination(db, state, node, &baseline, &candidate, authorization)? {
306        let (saved, auth) = load(db, id, false)?;
307        ensure!(
308            saved == *manifest && auth == *authorization,
309            "owner journal retry changed"
310        );
311        ensure!(
312            progress(db, id, manifest)?["pages_complete"] == true,
313            "activated owner journal is incomplete"
314        );
315    } else {
316        reserve(db, &candidate, false, authorization, manifest)?;
317    }
318    progress(db, id, manifest)
319}
320
321pub(crate) fn import_page(
322    db: &Connection,
323    state: &VerifiedState,
324    node: &gent_crypto::NodeIdentity,
325    id: &str,
326    index: usize,
327    body: &[u8],
328) -> Result<Value> {
329    ensure!(body.len() <= PAGE_BYTES, "owner journal page exceeds limit");
330    let (baseline, candidate, manifest, authorization) = incoming(db, id)?;
331    let late = check_destination(db, state, node, &baseline, &candidate, &authorization)?;
332    manifest.verify_page(index, body)?;
333    let saved: Option<Vec<u8>> = db
334        .query_row(
335            "SELECT body FROM owner_journal_pages WHERE id=?1 AND page=?2",
336            params![id, index],
337            |r| r.get(0),
338        )
339        .optional()?;
340    if let Some(saved) = saved {
341        ensure!(saved == body, "owner journal page changed after receipt");
342    } else {
343        ensure!(
344            !late,
345            "cannot repair an activated owner journal through import"
346        );
347        db.execute(
348            "INSERT INTO owner_journal_pages VALUES(?1,?2,?3)",
349            params![id, index, body],
350        )?;
351    }
352    let status = progress(db, id, &manifest)?;
353    if status["pages_complete"] == true {
354        require_complete(db, &baseline, &candidate, &authorization)?;
355    } else {
356        ensure!(!late, "activated owner journal is incomplete");
357    }
358    Ok(status)
359}
360
361impl Store {
362    /// Owner-only private export. Contains decision summaries, never signing keys.
363    pub fn owner_handoff_manifest(&self, credential: &str, id: &str) -> Result<Manifest> {
364        ensure!(hash(credential) == self.owner_hash, "unauthorized");
365        let tx = self.db.unchecked_transaction()?;
366        self.identity.state(&tx)?;
367        issued_for(&tx, id)?;
368        Ok(load(&tx, id, true)?.0)
369    }
370
371    pub fn owner_handoff_page(&self, credential: &str, id: &str, index: usize) -> Result<Vec<u8>> {
372        ensure!(hash(credential) == self.owner_hash, "unauthorized");
373        let tx = self.db.unchecked_transaction()?;
374        self.identity.state(&tx)?;
375        issued_for(&tx, id)?;
376        page(&tx, id, &load(&tx, id, true)?.0, index)
377    }
378
379    pub fn begin_owner_handoff_import(
380        &mut self,
381        credential: &str,
382        id: &str,
383        authorization: &SignedOwnerTransition,
384        manifest: &Manifest,
385    ) -> Result<Value> {
386        ensure!(hash(credential) == self.owner_hash, "unauthorized");
387        let tx = self
388            .db
389            .transaction_with_behavior(TransactionBehavior::Immediate)?;
390        let state = self.identity.state(&tx)?;
391        let status = begin_import(
392            &tx,
393            &state,
394            &self.identity.node,
395            id,
396            authorization,
397            manifest,
398        )?;
399        tx.commit()?;
400        Ok(status)
401    }
402
403    pub fn import_owner_handoff_page(
404        &mut self,
405        credential: &str,
406        id: &str,
407        index: usize,
408        body: &[u8],
409    ) -> Result<Value> {
410        ensure!(hash(credential) == self.owner_hash, "unauthorized");
411        ensure!(body.len() <= PAGE_BYTES, "owner journal page exceeds limit");
412        let tx = self
413            .db
414            .transaction_with_behavior(TransactionBehavior::Immediate)?;
415        let state = self.identity.state(&tx)?;
416        let status = import_page(&tx, &state, &self.identity.node, id, index, body)?;
417        tx.commit()?;
418        Ok(status)
419    }
420
421    pub fn owner_handoff_import_status(&self, credential: &str, id: &str) -> Result<Value> {
422        ensure!(hash(credential) == self.owner_hash, "unauthorized");
423        let tx = self.db.unchecked_transaction()?;
424        let (_, candidate, manifest, _) = incoming(&tx, id)?;
425        ensure!(
426            candidate.candidate.node.id == self.identity.node.id()
427                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
428            "owner journal belongs to another node"
429        );
430        progress(&tx, id, &manifest)
431    }
432}