Skip to main content

gent_daemon/store/handoff/
readiness.rs

1//! Durable readiness evidence, required before issuing a new signing stop.
2use super::*;
3use gent_crypto::{SignedConfigurationGrant, succession::readiness::SignedReadiness};
4
5const MAX_BYTES: usize = 64 * 1024 * 1024;
6
7pub(super) fn schema(db: &Connection, previous: i64) -> Result<()> {
8    let exists: bool = db.query_row(
9        "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='owner_readiness')",
10        [],
11        |r| r.get(0),
12    )?;
13    if !exists {
14        ensure!(previous < 23, "owner readiness storage is missing");
15        db.execute_batch("CREATE TABLE owner_readiness(id TEXT PRIMARY KEY CHECK(length(id)=36),local INTEGER NOT NULL CHECK(local IN (0,1)),candidate BLOB NOT NULL CHECK(length(candidate)<=8192),baseline BLOB NOT NULL CHECK(length(baseline)<=2097152),report BLOB NOT NULL CHECK(length(report)<=1572864));")?;
16    } else {
17        db.prepare("SELECT id,local,candidate,baseline,report FROM owner_readiness LIMIT 0")?;
18    }
19    Ok(())
20}
21
22pub(super) fn usage(db: &Connection) -> Result<Value> {
23    let (reports, bytes) = size(db)?;
24    ensure!(
25        reports <= LIMIT && bytes <= MAX_BYTES,
26        "owner readiness storage exceeds budget"
27    );
28    Ok(json!({"reports":reports,"stored_bytes":bytes,"max_reports":LIMIT,"max_bytes":MAX_BYTES}))
29}
30
31fn size(db: &Connection) -> Result<(usize, usize)> {
32    Ok(db.query_row("SELECT COUNT(*),COALESCE(SUM(length(candidate)+length(baseline)+length(report)),0) FROM owner_readiness", [], |r| Ok((r.get(0)?, r.get(1)?)))?)
33}
34
35fn grants(
36    db: &Connection,
37    report: &SignedReadiness,
38    candidate: &SignedOwnerCandidate,
39    local: bool,
40) -> Result<Vec<SignedConfigurationGrant>> {
41    let mut grants = Vec::new();
42    for peer in &report.readiness.peers {
43        let wire: Vec<u8> = if local {
44            db.query_row(
45                "SELECT grant FROM configuration_streams WHERE group_id=?1",
46                [peer.receipt.group()],
47                |r| r.get(0),
48            )?
49        } else {
50            let (pinned, grant): (Vec<u8>, Vec<u8>) = db.query_row(
51                "SELECT candidate,grant FROM owner_configuration_grants WHERE group_id=?1",
52                [peer.receipt.group()],
53                |r| Ok((r.get(0)?, r.get(1)?)),
54            )?;
55            ensure!(
56                pinned == candidate.encode()?,
57                "readiness grant belongs to another candidate"
58            );
59            grant
60        };
61        grants.push(SignedConfigurationGrant::decode(&wire)?);
62    }
63    Ok(grants)
64}
65
66fn load(
67    db: &Connection,
68    candidate: &SignedOwnerCandidate,
69    local: bool,
70) -> Result<Option<SignedReadiness>> {
71    type Saved = (bool, Vec<u8>, Vec<u8>, Vec<u8>);
72    let saved: Option<Saved> = db
73        .query_row(
74            "SELECT local,candidate,baseline,report FROM owner_readiness WHERE id=?1",
75            [&candidate.candidate.id],
76            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
77        )
78        .optional()?;
79    let Some((role, pinned, baseline, wire)) = saved else {
80        return Ok(None);
81    };
82    ensure!(
83        role == local && pinned == candidate.encode()?,
84        "owner readiness candidate or role changed"
85    );
86    let report = SignedReadiness::decode(&wire)?;
87    let state = restore(candidate, &baseline)?;
88    report.verify(
89        &state,
90        candidate,
91        &grants(db, &report, candidate, local)?,
92        report.readiness.issued_at,
93    )?;
94    Ok(Some(report))
95}
96
97fn save(
98    db: &Connection,
99    candidate: &SignedOwnerCandidate,
100    state: &VerifiedState,
101    report: &SignedReadiness,
102    local: bool,
103) -> Result<()> {
104    let candidate_wire = candidate.encode()?;
105    let baseline = state.signed().encode()?;
106    let report_wire = report.encode()?;
107    let (rows, bytes) = size(db)?;
108    ensure!(
109        rows < LIMIT
110            && bytes
111                .checked_add(candidate_wire.len() + baseline.len() + report_wire.len())
112                .is_some_and(|n| n <= MAX_BYTES),
113        "owner readiness storage budget exhausted"
114    );
115    db.execute(
116        "INSERT INTO owner_readiness VALUES(?1,?2,?3,?4,?5)",
117        params![
118            candidate.candidate.id,
119            local,
120            candidate_wire,
121            baseline,
122            report_wire
123        ],
124    )?;
125    Ok(())
126}
127
128pub(super) fn require(
129    db: &Connection,
130    state: &VerifiedState,
131    candidate: &SignedOwnerCandidate,
132    now: u64,
133) -> Result<()> {
134    let report = load(db, candidate, false)?
135        .context("successor readiness must be recorded before authorizing a handoff")?;
136    report.verify(
137        state,
138        candidate,
139        &grants(db, &report, candidate, false)?,
140        now,
141    )
142}
143
144impl Store {
145    /// Signs only after checking the successor's protected key, installed streams,
146    /// durable reader confirmations and local bidirectional data links.
147    pub fn owner_handoff_readiness(
148        &mut self,
149        credential: &str,
150        id: &str,
151    ) -> Result<SignedReadiness> {
152        ensure!(hash(credential) == self.owner_hash, "unauthorized");
153        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
154        let (key, candidate) = read_key(&candidate_path(&self.home, id)?)?;
155        let tx = self
156            .db
157            .transaction_with_behavior(TransactionBehavior::Immediate)?;
158        let (wire, baseline): (Vec<u8>, Vec<u8>) = tx.query_row(
159            "SELECT candidate,baseline FROM owner_candidates WHERE id=?1",
160            [id],
161            |r| Ok((r.get(0)?, r.get(1)?)),
162        )?;
163        ensure!(
164            wire == candidate.encode()?
165                && candidate.candidate.node.id == self.identity.node.id()
166                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
167            "readiness candidate belongs to another node"
168        );
169        self.identity.state(&tx)?;
170        if let Some(report) = load(&tx, &candidate, true)? {
171            return Ok(report);
172        }
173        let pinned = restore(&candidate, &baseline)?;
174        let state = self.identity.state(&tx)?;
175        ensure!(
176            state.checkpoint() == pinned.checkpoint(),
177            "authority changed since handoff preparation"
178        );
179        let timestamp = requests::clock(&tx, now())? as u64;
180        candidate.verify(&state, timestamp)?;
181        let connections = activation::readiness(&tx, &self.identity.node, &state, &candidate)?;
182        let report = self.identity.node.sign_owner_readiness(
183            &state,
184            &key,
185            &candidate,
186            &connections,
187            timestamp,
188        )?;
189        save(&tx, &candidate, &state, &report, true)?;
190        tx.commit()?;
191        Ok(report)
192    }
193
194    /// Records evidence on the source without freezing it. New authorization
195    /// verifies the same evidence again at the decision's current checkpoint.
196    pub fn record_owner_readiness(
197        &mut self,
198        credential: &str,
199        candidate: &SignedOwnerCandidate,
200        report: &SignedReadiness,
201    ) -> Result<()> {
202        ensure!(hash(credential) == self.owner_hash, "unauthorized");
203        report.encode()?;
204        let tx = self
205            .db
206            .transaction_with_behavior(TransactionBehavior::Immediate)?;
207        let state = self.identity.state(&tx)?;
208        if let Some(previous) = load(&tx, candidate, false)? {
209            ensure!(previous == *report, "owner readiness report changed");
210            return Ok(());
211        }
212        self.identity.signing_owner(&tx)?;
213        ensure!(
214            candidate.candidate.node.id != self.identity.node.id(),
215            "owner handoff requires another node"
216        );
217        let timestamp = requests::clock(&tx, now())? as u64;
218        report.verify(
219            &state,
220            candidate,
221            &grants(&tx, report, candidate, false)?,
222            timestamp,
223        )?;
224        save(&tx, candidate, &state, report, false)?;
225        tx.commit()?;
226        Ok(())
227    }
228}