Skip to main content

gent_daemon/store/peer_configuration/
proposals.rs

1use super::*;
2
3impl Store {
4    /// Reapply a retained edit against the current committed authority. Calling
5    /// this again at the same head returns identical ciphertext. A changed head
6    /// creates a new candidate with the same operation ID and salted intent.
7    /// The transport checks for an existing service receipt before calling this.
8    pub fn prepare_configuration_proposal(&self, id: &str) -> Result<Commit> {
9        self.prepare_configuration_for(&Queued {
10            origin: self.identity.node.id().into(),
11            id: id.into(),
12            operation: id.into(),
13        })
14    }
15
16    pub(crate) fn prepare_configuration_for(&self, queued: &Queued) -> Result<Commit> {
17        let origin = queued.origin.as_str();
18        let id = queued.id.as_str();
19        let tx = self.db.unchecked_transaction()?;
20        let state = self.identity.state(&tx)?;
21        ensure!(
22            state.state().peer.is_some(),
23            "peer configuration is not active"
24        );
25        let edit: Vec<u8> = tx.query_row("SELECT p.body FROM configuration_pending p JOIN configuration_edits e ON e.origin=p.origin AND e.id=p.id WHERE p.origin=?1 AND p.id=?2 AND e.result IS NULL", params![origin, id], |r| r.get(0))?;
26        let (head, capability): (Vec<u8>, Option<Vec<u8>>) = tx.query_row(
27            "SELECT head,capability FROM peer_configuration WHERE singleton=1 AND active=1",
28            [],
29            |r| Ok((r.get(0)?, r.get(1)?)),
30        )?;
31        let head: Head = serde_json::from_slice(&head)?;
32        let capability =
33            Zeroizing::new(capability.context("this node cannot administer configuration")?);
34        let capability = WriteCapability::from_secret(capability.as_slice().try_into()?);
35        let saved: Option<SavedProposal> = tx.query_row("SELECT salt,intent,candidate FROM peer_configuration_requests WHERE origin=?1 AND id=?2", params![origin, id], |r| Ok(SavedProposal { salt: Zeroizing::new(r.get(0)?), intent: r.get(1)?, candidate: r.get(2)? })).optional()?;
36        let salt = match &saved {
37            Some(saved) => Zeroizing::new(saved.salt.as_slice().try_into()?),
38            None => Zeroizing::new(random_salt()),
39        };
40        let intent = crypto::intent(&salt, &edit);
41        if let Some(saved) = &saved {
42            ensure!(
43                saved.intent == intent,
44                "pending configuration intent changed"
45            );
46            if let Some(candidate) = &saved.candidate {
47                let candidate: Commit = serde_json::from_slice(candidate)?;
48                ensure!(
49                    candidate.header.origin == self.identity.node.id()
50                        && candidate.header.operation == queued.operation
51                        && candidate.header.intent == intent,
52                    "saved proposal belongs to another operation"
53                );
54                if candidate.header.previous == head {
55                    let valid = self.configuration_candidate(
56                        &tx,
57                        &state,
58                        candidate.header.clone(),
59                        origin,
60                        id,
61                        &edit,
62                    )?;
63                    let opened = envelope::open(&self.identity.node, &state, &head, &candidate)?;
64                    let same_decision = valid.state.peer.as_ref().and_then(|p| p.request.as_ref())
65                        == opened
66                            .state
67                            .state()
68                            .peer
69                            .as_ref()
70                            .and_then(|p| p.request.as_ref());
71                    if same_decision && opened.state.require_fresh(now() as u64).is_ok() {
72                        return Ok(candidate);
73                    }
74                }
75            }
76        }
77        let next = WriteCapability::generate()?;
78        let header = header(
79            &state,
80            head,
81            self.identity.node.id(),
82            &queued.operation,
83            intent,
84            &next,
85        );
86        let candidate =
87            self.configuration_candidate(&tx, &state, header.clone(), origin, id, &edit)?;
88        let commit = capability.seal(header, &envelope::seal(&candidate, &next)?)?;
89        let wire = serde_json::to_vec(&commit)?;
90        let bytes: u64 = tx.query_row("SELECT COALESCE(SUM(length(candidate)),0) FROM peer_configuration_requests WHERE origin!=?1 OR id!=?2", params![origin, id], |r| r.get(0))?;
91        ensure!(
92            bytes.saturating_add(wire.len() as u64) <= 64 * 1024 * 1024,
93            "configuration proposal capacity reached"
94        );
95        tx.execute("INSERT INTO peer_configuration_requests VALUES(?1,?2,?3,?4,?5) ON CONFLICT(origin,id) DO UPDATE SET candidate=excluded.candidate", params![origin, id, salt.as_slice(), intent.as_slice(), wire])?;
96        tx.commit()?;
97        Ok(commit)
98    }
99    fn configuration_candidate(
100        &self,
101        db: &Connection,
102        state: &VerifiedState,
103        header: Header,
104        origin: &str,
105        id: &str,
106        body: &[u8],
107    ) -> Result<gent_crypto::SignedState> {
108        let edit = serde_json::from_slice(body)?;
109        let mut request = gent_crypto::peer::Request {
110            origin: origin.into(),
111            id: id.into(),
112            fingerprint: configuration::fingerprint(&edit)?,
113            rejection: None,
114        };
115        let signer =
116            NodeSigner::new(&self.identity.node, header.clone())?.with_request(request.clone())?;
117        let mut session = self.network_session(db, state.clone());
118        session.timestamp = session.timestamp.max(state.state().issued_at.try_into()?);
119        match session.revision_for_edit_with(origin, &edit, &signer) {
120            Ok(candidate) => Ok(candidate),
121            Err(error)
122                if origin != self.identity.node.id()
123                    && !error
124                        .chain()
125                        .any(|e| e.is::<rusqlite::Error>() || e.is::<std::io::Error>()) =>
126            {
127                request.rejection =
128                    Some(configuration::storage::rejection_reason(error.to_string()));
129                let signer = NodeSigner::new(&self.identity.node, header)?.with_request(request)?;
130                state.renew(&signer, session.timestamp as u64)
131            }
132            Err(error) => Err(error),
133        }
134    }
135}