Skip to main content

gent_crypto/authority/succession/
candidate.rs

1use super::*;
2
3pub const MAX_CANDIDATE_BYTES: usize = 8192;
4pub const CANDIDATE_LIFETIME: u64 = 15 * 60;
5const NODE_DOMAIN: &[u8] = b"gent/owner-candidate/v1\0";
6const KEY_DOMAIN: &[u8] = b"gent/owner-candidate-key/v1\0";
7const CANDIDATE_DOMAIN: &[u8] = b"gent/owner-candidate-record/v1\0";
8
9#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(deny_unknown_fields)]
11pub struct OwnerSuccessor {
12    pub node: ReplacedNode,
13    pub candidate: Digest,
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub journal: Option<Digest>,
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
19#[serde(deny_unknown_fields)]
20pub struct OwnerCandidate {
21    pub version: u32,
22    pub id: String,
23    pub anchor: TrustAnchor,
24    pub base: Checkpoint,
25    pub node: ReplacedNode,
26    pub owner_key: PublicKey,
27    pub issued_at: u64,
28    pub expires_at: u64,
29}
30
31#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
32#[serde(deny_unknown_fields)]
33pub struct SignedOwnerCandidate {
34    pub candidate: OwnerCandidate,
35    pub node_signature: Vec<u8>,
36    pub key_signature: Vec<u8>,
37}
38
39impl SignedOwnerCandidate {
40    pub fn encode(&self) -> Result<Vec<u8>> {
41        encode(self, MAX_CANDIDATE_BYTES)
42    }
43    pub fn decode(bytes: &[u8]) -> Result<Self> {
44        decode(bytes, MAX_CANDIDATE_BYTES)
45    }
46    pub fn digest(&self) -> Result<Digest> {
47        digest(CANDIDATE_DOMAIN, self, MAX_CANDIDATE_BYTES)
48    }
49
50    /// Verify against independently trusted live state before approving a signer.
51    pub fn verify(&self, state: &VerifiedState, now: u64) -> Result<()> {
52        let proposal = &self.candidate;
53        ensure!(
54            proposal.version == 1
55                && &proposal.anchor == state.anchor()
56                && &proposal.base == state.checkpoint(),
57            "owner candidate has a different cluster or checkpoint"
58        );
59        id(&proposal.id)?;
60        lifetime(proposal.issued_at, proposal.expires_at, CANDIDATE_LIFETIME)?;
61        fresh(proposal.issued_at, proposal.expires_at, now)?;
62        ensure!(
63            proposal.issued_at >= state.state().issued_at,
64            "candidate predates its state"
65        );
66        ensure!(
67            state
68                .authorize_node(&proposal.node.id, &proposal.node.signing_key, now)?
69                .hosted_by
70                .is_none(),
71            "owner candidate must be a native node"
72        );
73        public_key(&proposal.owner_key)?;
74        ensure!(
75            !owner_keys(&state.state().owner_transitions, state.state().owner_key)
76                .contains(&proposal.owner_key)
77                && !state.state().retired_keys.contains(&proposal.owner_key)
78                && state
79                    .state()
80                    .nodes
81                    .values()
82                    .all(|n| n.signing_key != proposal.owner_key),
83            "candidate must use a fresh separate owner key"
84        );
85        verify(
86            &proposal.node.signing_key,
87            NODE_DOMAIN,
88            proposal,
89            &self.node_signature,
90            MAX_CANDIDATE_BYTES,
91        )?;
92        verify(
93            &proposal.owner_key,
94            KEY_DOMAIN,
95            proposal,
96            &self.key_signature,
97            MAX_CANDIDATE_BYTES,
98        )?;
99        self.encode()?;
100        Ok(())
101    }
102}
103
104impl NodeIdentity {
105    pub fn prepare_owner_candidate(
106        &self,
107        state: &VerifiedState,
108        key: &OwnerKey,
109        request: &str,
110        now: u64,
111    ) -> Result<SignedOwnerCandidate> {
112        let candidate = OwnerCandidate {
113            version: 1,
114            id: request.into(),
115            anchor: state.anchor().clone(),
116            base: state.checkpoint().clone(),
117            node: ReplacedNode {
118                id: self.id().into(),
119                signing_key: self.public_key(),
120            },
121            owner_key: key.public_key(),
122            issued_at: now,
123            expires_at: now
124                .checked_add(CANDIDATE_LIFETIME)
125                .context("timestamp overflow")?,
126        };
127        let node_signature = self
128            .key
129            .sign(&signing_input(
130                NODE_DOMAIN,
131                &candidate,
132                MAX_CANDIDATE_BYTES,
133            )?)
134            .to_bytes()
135            .to_vec();
136        let key_signature = key
137            .0
138            .sign(&signing_input(KEY_DOMAIN, &candidate, MAX_CANDIDATE_BYTES)?)
139            .to_bytes()
140            .to_vec();
141        let signed = SignedOwnerCandidate {
142            candidate,
143            node_signature,
144            key_signature,
145        };
146        signed.verify(state, now)?;
147        Ok(signed)
148    }
149}
150
151impl VerifiedState {
152    /// Persist a write fence before returning this authorization to another node.
153    pub fn authorize_owner_candidate(
154        &self,
155        owner: &OwnerKey,
156        candidate: &SignedOwnerCandidate,
157        now: u64,
158    ) -> Result<SignedOwnerTransition> {
159        self.authorize_candidate(owner, candidate, None, now)
160    }
161
162    /// The caller snapshots completed decisions in the same transaction that
163    /// freezes signing. The digest authenticates that exact transfer manifest.
164    pub fn authorize_owner_candidate_with_journal(
165        &self,
166        owner: &OwnerKey,
167        candidate: &SignedOwnerCandidate,
168        journal: Digest,
169        now: u64,
170    ) -> Result<SignedOwnerTransition> {
171        self.authorize_candidate(owner, candidate, Some(journal), now)
172    }
173
174    fn authorize_candidate(
175        &self,
176        owner: &OwnerKey,
177        candidate: &SignedOwnerCandidate,
178        journal: Option<Digest>,
179        now: u64,
180    ) -> Result<SignedOwnerTransition> {
181        ensure!(
182            owner.public_key() == self.state().owner_key,
183            "wrong current owner authority"
184        );
185        candidate.verify(self, now)?;
186        ensure!(
187            self.state().owner_transitions.len() < MAX_OWNER_TRANSITIONS,
188            "owner succession history is full"
189        );
190        let transition = OwnerTransition {
191            version: 1,
192            anchor: self.anchor().clone(),
193            epoch: self.owner_epoch() + 1,
194            previous: self
195                .state()
196                .owner_transitions
197                .last()
198                .map(SignedOwnerTransition::digest)
199                .transpose()?
200                .unwrap_or(self.anchor().genesis_hash),
201            base: self.checkpoint().clone(),
202            owner_key: candidate.candidate.owner_key,
203            successor: Some(OwnerSuccessor {
204                node: candidate.candidate.node.clone(),
205                candidate: candidate.digest()?,
206                journal,
207            }),
208            issued_at: now,
209        };
210        let signature = owner
211            .0
212            .sign(&signing_input(
213                DOMAIN,
214                &transition,
215                MAX_OWNER_TRANSITION_BYTES,
216            )?)
217            .to_bytes()
218            .to_vec();
219        let signed = SignedOwnerTransition {
220            transition,
221            signature,
222        };
223        self.verify_owner_authorization(candidate, &signed)?;
224        Ok(signed)
225    }
226
227    /// Verifies authorization at its original issue time. Once issued, retrying
228    /// completion after the candidate deadline must preserve the same decision.
229    pub fn verify_owner_authorization(
230        &self,
231        candidate: &SignedOwnerCandidate,
232        authorization: &SignedOwnerTransition,
233    ) -> Result<()> {
234        candidate.verify(self, authorization.transition.issued_at)?;
235        let expected = OwnerSuccessor {
236            node: candidate.candidate.node.clone(),
237            candidate: candidate.digest()?,
238            journal: authorization
239                .transition
240                .successor
241                .as_ref()
242                .and_then(|s| s.journal),
243        };
244        ensure!(
245            authorization.transition.base == *self.checkpoint()
246                && authorization.transition.owner_key == candidate.candidate.owner_key
247                && authorization.transition.successor.as_ref() == Some(&expected),
248            "owner authorization does not match candidate"
249        );
250        let mut chain = self.state().owner_transitions.clone();
251        chain.push(authorization.clone());
252        verify_lineage(self.anchor(), &chain)?;
253        Ok(())
254    }
255
256    pub fn accept_owner_authorization(
257        &self,
258        key: &OwnerKey,
259        candidate: &SignedOwnerCandidate,
260        authorization: &SignedOwnerTransition,
261        now: u64,
262    ) -> Result<SignedState> {
263        self.verify_owner_authorization(candidate, authorization)?;
264        ensure!(
265            now >= authorization.transition.issued_at,
266            "owner completion clock moved backwards"
267        );
268        self.sign_owner_transition(key, authorization.clone())
269    }
270}