1use alloc::vec::Vec;
17use core::fmt;
18
19use rand_core::CryptoRng;
20use zeroize::Zeroizing;
21
22use crate::key::{PrivateKey, PublicKey};
23use crate::signature::Signature;
24
25const INVALID_KEY_IDENTIFIER: u64 = u64::MAX;
27const TREE_HEADER_SIZE: usize = 4 * 8;
29const LEVEL_HEADER_SIZE: usize = 32 + 2 * 8;
31const ENTRY_SIZE: usize = 32 + 64;
33
34struct Entry {
36 private_key: Option<PrivateKey>,
37 signature: Signature,
38}
39
40pub struct VotingKeyTree {
42 start_epoch: u32,
43 end_epoch: u32,
44 last_used_epoch: Option<u32>,
45 last_wiped_epoch: Option<u32>,
46 root_public_key: PublicKey,
47 entries: Vec<Entry>,
49}
50
51impl VotingKeyTree {
52 pub fn generate<R: CryptoRng + ?Sized>(
56 rng: &mut R,
57 start_epoch: u32,
58 end_epoch: u32,
59 ) -> Result<Self, VotingKeyError> {
60 if start_epoch == 0 || end_epoch < start_epoch {
61 return Err(VotingKeyError::InvalidEpochs {
62 start: start_epoch.into(),
63 end: end_epoch.into(),
64 });
65 }
66 let root = PrivateKey::generate_with_rng(rng);
67 let mut entries: Vec<_> = (start_epoch..=end_epoch)
69 .rev()
70 .map(|epoch| {
71 let private_key = PrivateKey::generate_with_rng(rng);
72 let signature = root.sign(&[
73 &PublicKey::from_private_key(&private_key).0,
74 &u64::from(epoch).to_le_bytes(),
75 ]);
76 Entry {
77 private_key: Some(private_key),
78 signature,
79 }
80 })
81 .collect();
82 entries.reverse();
83 Ok(Self {
84 start_epoch,
85 end_epoch,
86 last_used_epoch: None,
87 last_wiped_epoch: None,
88 root_public_key: PublicKey::from_private_key(&root),
89 entries,
90 })
91 }
92
93 pub fn from_bytes(bytes: &[u8]) -> Result<Self, VotingKeyError> {
96 let u64_at = |offset: usize| {
97 u64::from_le_bytes(bytes[offset..offset + 8].try_into().expect("8 bytes"))
98 };
99 if bytes.len() < TREE_HEADER_SIZE + LEVEL_HEADER_SIZE {
100 return Err(VotingKeyError::TooShort);
101 }
102 let (start, end) = (u64_at(0), u64_at(8));
103 let (level_start, level_end) = (u64_at(64), u64_at(72));
104 if (level_start, level_end) != (start, end) {
105 return Err(VotingKeyError::InconsistentEpochs);
106 }
107 let epoch = |value: u64| u32::try_from(value).ok().filter(|&epoch| epoch != 0);
108 let (Some(start_epoch), Some(end_epoch)) = (epoch(start), epoch(end)) else {
109 return Err(VotingKeyError::InvalidEpochs { start, end });
110 };
111 if end_epoch < start_epoch {
112 return Err(VotingKeyError::InvalidEpochs { start, end });
113 }
114 let count = (end_epoch - start_epoch) as usize + 1;
115 let expected = TREE_HEADER_SIZE + LEVEL_HEADER_SIZE + count * ENTRY_SIZE;
116 if bytes.len() != expected {
117 return Err(VotingKeyError::SizeMismatch {
118 expected,
119 actual: bytes.len(),
120 });
121 }
122 let marker = |value: u64| match value {
124 INVALID_KEY_IDENTIFIER => Ok(None),
125 value => epoch(value)
126 .filter(|epoch| (start_epoch..=end_epoch).contains(epoch))
127 .map(Some)
128 .ok_or(VotingKeyError::InvalidKeyIdentifier(value)),
129 };
130 let last_used_epoch = marker(u64_at(16))?;
131 let last_wiped_epoch = marker(u64_at(24))?;
132
133 let mut entries: Vec<_> = bytes[TREE_HEADER_SIZE + LEVEL_HEADER_SIZE..]
134 .chunks(ENTRY_SIZE)
135 .map(|entry| {
136 let private_key: &[u8; 32] = entry[..32].try_into().expect("32 bytes");
137 Entry {
138 private_key: (*private_key != [0; 32])
139 .then(|| PrivateKey::from_bytes(private_key)),
140 signature: Signature(entry[32..].try_into().expect("64 bytes")),
141 }
142 })
143 .collect();
144 entries.reverse();
145 Ok(Self {
146 start_epoch,
147 end_epoch,
148 last_used_epoch,
149 last_wiped_epoch,
150 root_public_key: PublicKey(bytes[32..64].try_into().expect("32 bytes")),
151 entries,
152 })
153 }
154
155 pub fn to_bytes(&self) -> Zeroizing<Vec<u8>> {
157 let marker = |epoch: Option<u32>| epoch.map_or(INVALID_KEY_IDENTIFIER, u64::from);
158 let mut bytes = Zeroizing::new(Vec::with_capacity(
159 TREE_HEADER_SIZE + LEVEL_HEADER_SIZE + self.entries.len() * ENTRY_SIZE,
160 ));
161 for value in [
162 self.start_epoch.into(),
163 self.end_epoch.into(),
164 marker(self.last_used_epoch),
165 marker(self.last_wiped_epoch),
166 ] {
167 bytes.extend_from_slice(&u64::to_le_bytes(value));
168 }
169 bytes.extend_from_slice(&self.root_public_key.0);
170 bytes.extend_from_slice(&u64::from(self.start_epoch).to_le_bytes());
171 bytes.extend_from_slice(&u64::from(self.end_epoch).to_le_bytes());
172 for entry in self.entries.iter().rev() {
173 match &entry.private_key {
174 Some(private_key) => bytes.extend_from_slice(private_key.as_bytes()),
175 None => bytes.extend_from_slice(&[0; 32]),
176 }
177 bytes.extend_from_slice(&entry.signature.0);
178 }
179 bytes
180 }
181
182 pub fn can_sign(&self, epoch: u32) -> bool {
185 self.last_used_epoch.is_none_or(|last| epoch >= last)
186 && (self.start_epoch..=self.end_epoch).contains(&epoch)
187 && self.entries[(epoch - self.start_epoch) as usize]
188 .private_key
189 .is_some()
190 }
191
192 pub fn sign(&mut self, epoch: u32, message: &[&[u8]]) -> Option<[u8; 192]> {
197 if !self.can_sign(epoch) {
198 return None;
199 }
200 let entry = &self.entries[(epoch - self.start_epoch) as usize];
201 let private_key = entry.private_key.as_ref()?;
202 let mut out = [0; 192];
203 out[..32].copy_from_slice(&self.root_public_key.0);
204 out[32..96].copy_from_slice(&entry.signature.0);
205 out[96..128].copy_from_slice(&PublicKey::from_private_key(private_key).0);
206 out[128..].copy_from_slice(&private_key.sign(message).0);
207 self.last_used_epoch = Some(epoch);
208 Some(out)
209 }
210
211 pub fn wipe_through(&mut self, epoch: u32) {
214 if epoch < self.start_epoch || self.last_wiped_epoch.is_some_and(|last| epoch < last) {
215 return;
216 }
217 let epoch = epoch.min(self.end_epoch);
218 for entry in &mut self.entries[..=(epoch - self.start_epoch) as usize] {
219 entry.private_key = None;
220 }
221 self.last_wiped_epoch = Some(epoch);
222 }
223
224 pub fn public_key(&self) -> PublicKey {
226 self.root_public_key
227 }
228
229 pub fn start_epoch(&self) -> u32 {
230 self.start_epoch
231 }
232
233 pub fn end_epoch(&self) -> u32 {
234 self.end_epoch
235 }
236
237 pub fn last_used_epoch(&self) -> Option<u32> {
239 self.last_used_epoch
240 }
241
242 pub fn last_wiped_epoch(&self) -> Option<u32> {
244 self.last_wiped_epoch
245 }
246
247 pub fn remaining_keys(&self) -> usize {
249 self.entries
250 .iter()
251 .filter(|entry| entry.private_key.is_some())
252 .count()
253 }
254
255 pub fn verify(&self) -> Result<(), u32> {
258 for (epoch, entry) in (self.start_epoch..=self.end_epoch).zip(&self.entries) {
259 let Some(private_key) = &entry.private_key else {
260 continue;
261 };
262 let public_key = PublicKey::from_private_key(private_key);
263 if !self.root_public_key.verify(
264 &[&public_key.0, &u64::from(epoch).to_le_bytes()],
265 &entry.signature,
266 ) {
267 return Err(epoch);
268 }
269 }
270 Ok(())
271 }
272}
273
274impl fmt::Debug for VotingKeyTree {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 f.debug_struct("VotingKeyTree")
277 .field("start_epoch", &self.start_epoch)
278 .field("end_epoch", &self.end_epoch)
279 .field("last_used_epoch", &self.last_used_epoch)
280 .field("last_wiped_epoch", &self.last_wiped_epoch)
281 .field("root_public_key", &self.root_public_key)
282 .finish_non_exhaustive()
283 }
284}
285
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub enum VotingKeyError {
288 TooShort,
290 SizeMismatch { expected: usize, actual: usize },
292 InvalidEpochs { start: u64, end: u64 },
294 InconsistentEpochs,
296 InvalidKeyIdentifier(u64),
298}
299
300impl fmt::Display for VotingKeyError {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 match self {
303 Self::TooShort => f.write_str("投票鍵のファイルのヘッダーの長さに足りません"),
304 Self::SizeMismatch { expected, actual } => write!(
305 f,
306 "期間からは {expected} バイトのはずですが、{actual} バイトでした"
307 ),
308 Self::InvalidEpochs { start, end } => write!(
309 f,
310 "期間(エポック {start} から {end} まで)が正しくありません"
311 ),
312 Self::InconsistentEpochs => f.write_str("先頭の期間と、公開鍵に続く期間が違います"),
313 Self::InvalidKeyIdentifier(value) => {
314 write!(f, "使った鍵か消した鍵の番号 {value} が期間の中にありません")
315 }
316 }
317 }
318}
319
320impl core::error::Error for VotingKeyError {}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 struct Counter(u8);
328
329 impl rand_core::TryRng for Counter {
330 type Error = core::convert::Infallible;
331
332 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
333 unimplemented!("only fill_bytes is used")
334 }
335
336 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
337 unimplemented!("only fill_bytes is used")
338 }
339
340 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
341 for byte in dst {
342 self.0 = self.0.wrapping_add(1);
343 *byte = self.0;
344 }
345 Ok(())
346 }
347 }
348
349 impl rand_core::TryCryptoRng for Counter {}
350
351 #[test]
352 fn signs_with_the_key_of_the_epoch_and_never_goes_back() {
353 let mut tree = VotingKeyTree::generate(&mut Counter(0), 5, 7).unwrap();
354 assert!(!tree.can_sign(4) && !tree.can_sign(8));
355 assert!(tree.sign(4, &[b"x"]).is_none());
356
357 let signature = tree.sign(6, &[b"ab", b"c"]).unwrap();
358 assert_eq!(signature[..32], tree.public_key().0);
359 let bottom = PublicKey(signature[96..128].try_into().unwrap());
360 assert!(tree.public_key().verify(
361 &[&bottom.0, &6u64.to_le_bytes()],
362 &Signature(signature[32..96].try_into().unwrap())
363 ));
364 assert!(bottom.verify(&[b"abc"], &Signature(signature[128..].try_into().unwrap())));
365 assert_eq!(tree.last_used_epoch(), Some(6));
366 assert!(tree.can_sign(6));
368 assert!(!tree.can_sign(5));
369
370 let reread = VotingKeyTree::from_bytes(&tree.to_bytes()).unwrap();
372 assert_eq!(reread.last_used_epoch(), Some(6));
373 assert!(!reread.can_sign(5));
374 }
375
376 #[test]
377 fn wipes_keys_through_an_epoch() {
378 let mut tree = VotingKeyTree::generate(&mut Counter(0), 5, 7).unwrap();
379 tree.wipe_through(4);
380 assert_eq!(tree.remaining_keys(), 3);
381 tree.wipe_through(5);
382 assert_eq!(
383 (tree.remaining_keys(), tree.last_wiped_epoch()),
384 (2, Some(5))
385 );
386 assert!(!tree.can_sign(5) && tree.can_sign(6));
387 tree.wipe_through(4);
389 assert_eq!(tree.last_wiped_epoch(), Some(5));
390
391 let reread = VotingKeyTree::from_bytes(&tree.to_bytes()).unwrap();
392 assert_eq!(
393 (reread.remaining_keys(), reread.last_wiped_epoch()),
394 (2, Some(5))
395 );
396 assert_eq!(reread.verify(), Ok(()));
397
398 tree.wipe_through(9);
399 assert_eq!(
400 (tree.remaining_keys(), tree.last_wiped_epoch()),
401 (0, Some(7))
402 );
403 assert!(!tree.can_sign(7));
404 }
405
406 #[test]
407 fn writes_the_catapult_layout() {
408 let tree = VotingKeyTree::generate(&mut Counter(0), 5, 7).unwrap();
409 let bytes = tree.to_bytes();
410 assert_eq!(bytes.len(), 32 + 48 + 3 * 96);
411 assert_eq!(bytes[..8], 5u64.to_le_bytes());
412 assert_eq!(bytes[8..16], 7u64.to_le_bytes());
413 assert_eq!(bytes[16..32], [0xFF; 16]);
414
415 let root: [u8; 32] = core::array::from_fn(|i| i as u8 + 1);
417 let root = PrivateKey::from_bytes(&root);
418 assert_eq!(tree.public_key(), PublicKey::from_private_key(&root));
419 assert_eq!(bytes[32..64], tree.public_key().0);
420 assert!(!bytes.windows(32).any(|window| window == root.as_bytes()));
421 assert_eq!(bytes[64..72], 5u64.to_le_bytes());
422 assert_eq!(bytes[72..80], 7u64.to_le_bytes());
423
424 let first: [u8; 32] = core::array::from_fn(|i| i as u8 + 33);
426 assert_eq!(bytes[80..112], first);
427 let signature = root.sign(&[
428 &PublicKey::from_private_key(&PrivateKey::from_bytes(&first)).0,
429 &7u64.to_le_bytes(),
430 ]);
431 assert_eq!(bytes[112..176], signature.0);
432 assert_eq!(tree.verify(), Ok(()));
433 }
434
435 #[test]
436 fn reads_back_what_it_writes() {
437 let tree = VotingKeyTree::generate(&mut Counter(0), 1, 4).unwrap();
438 let read = VotingKeyTree::from_bytes(&tree.to_bytes()).unwrap();
439 assert_eq!(*read.to_bytes(), *tree.to_bytes());
440 assert_eq!((read.start_epoch(), read.end_epoch()), (1, 4));
441 assert_eq!(read.public_key(), tree.public_key());
442 assert_eq!(read.remaining_keys(), 4);
443 assert_eq!(read.verify(), Ok(()));
444 }
445
446 #[test]
447 fn reads_keys_that_the_node_used_and_wiped() {
448 let tree = VotingKeyTree::generate(&mut Counter(0), 1, 4).unwrap();
449 let mut bytes = tree.to_bytes();
450 bytes[16..24].copy_from_slice(&3u64.to_le_bytes());
452 bytes[24..32].copy_from_slice(&2u64.to_le_bytes());
453 for index in [2, 3] {
454 let offset = 80 + index * 96;
455 bytes[offset..offset + 32].fill(0);
456 }
457 let read = VotingKeyTree::from_bytes(&bytes).unwrap();
458 assert_eq!(read.last_used_epoch(), Some(3));
459 assert_eq!(read.last_wiped_epoch(), Some(2));
460 assert_eq!(read.remaining_keys(), 2);
461 assert_eq!(read.verify(), Ok(()));
462 assert_eq!(*read.to_bytes(), *bytes);
463 }
464
465 #[test]
466 fn finds_a_key_that_the_root_did_not_sign() {
467 let tree = VotingKeyTree::generate(&mut Counter(0), 1, 4).unwrap();
468 let mut bytes = tree.to_bytes();
469 bytes[80 + 2 * 96 + 32] ^= 1;
471 assert_eq!(VotingKeyTree::from_bytes(&bytes).unwrap().verify(), Err(2));
472 }
473
474 #[test]
475 fn rejects_broken_files() {
476 let bytes = VotingKeyTree::generate(&mut Counter(0), 1, 4)
477 .unwrap()
478 .to_bytes();
479 let with = |values: &[(usize, u64)]| {
480 let mut bytes = bytes.to_vec();
481 for &(offset, value) in values {
482 bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
483 }
484 bytes
485 };
486 for (name, broken, error) in [
487 ("short", bytes[..40].to_vec(), VotingKeyError::TooShort),
488 (
489 "long",
490 [bytes.as_slice(), &[0]].concat(),
491 VotingKeyError::SizeMismatch {
492 expected: bytes.len(),
493 actual: bytes.len() + 1,
494 },
495 ),
496 (
497 "level",
498 with(&[(64, 2)]),
499 VotingKeyError::InconsistentEpochs,
500 ),
501 (
502 "zero",
503 with(&[(0, 0), (64, 0)]),
504 VotingKeyError::InvalidEpochs { start: 0, end: 4 },
505 ),
506 (
507 "used",
508 with(&[(16, 5)]),
509 VotingKeyError::InvalidKeyIdentifier(5),
510 ),
511 ] {
512 assert_eq!(
513 VotingKeyTree::from_bytes(&broken).unwrap_err(),
514 error,
515 "{name}"
516 );
517 }
518 assert_eq!(
519 VotingKeyTree::generate(&mut Counter(0), 0, 4).unwrap_err(),
520 VotingKeyError::InvalidEpochs { start: 0, end: 4 }
521 );
522 assert_eq!(
523 VotingKeyTree::generate(&mut Counter(0), 5, 4).unwrap_err(),
524 VotingKeyError::InvalidEpochs { start: 5, end: 4 }
525 );
526 }
527}