1use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
6use nibkeep_base::{ChangeId, EntityId, Hash, SpaceId};
7use nibkeep_crypto::rand_core::CryptoRng;
8use nibkeep_crypto::{Envelope, Key, Signature, SigningKey, VerifyingKey};
9
10use crate::{LogError, SpaceKeys};
11
12const ACCOUNTS_CONTEXT: &str = "nibkeep 2026-11 accounts";
14
15const SIGNATURE_CONTEXT: &str = "nibkeep account";
17
18const VERSION: u64 = 1;
20
21pub const MAX_PAGE_LEN: usize = 4 * 1024 * 1024;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub enum PageKind {
31 Head,
33 Blobs(u8),
35 Copies(u8),
37}
38
39impl PageKind {
40 #[must_use]
43 pub fn number(self) -> u16 {
44 match self {
45 Self::Head => 0,
46 Self::Blobs(byte) => 0x100 + u16::from(byte),
47 Self::Copies(byte) => 0x200 + u16::from(byte),
48 }
49 }
50
51 #[must_use]
53 pub fn from_number(number: u64) -> Option<Self> {
54 match number {
55 0 => Some(Self::Head),
56 0x100..=0x1FF => u8::try_from(number - 0x100).ok().map(Self::Blobs),
57 0x200..=0x2FF => u8::try_from(number - 0x200).ok().map(Self::Copies),
58 _ => None,
59 }
60 }
61}
62
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum DeviceRole {
67 #[default]
69 Everyday,
70 Archive,
72}
73
74impl DeviceRole {
75 #[must_use]
77 pub const fn as_str(self) -> &'static str {
78 match self {
79 Self::Everyday => "everyday",
80 Self::Archive => "archive",
81 }
82 }
83
84 #[must_use]
86 pub fn from_name(name: &str) -> Option<Self> {
87 match name {
88 "everyday" => Some(Self::Everyday),
89 "archive" => Some(Self::Archive),
90 _ => None,
91 }
92 }
93}
94
95#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Head {
99 pub disk: Hash,
101 pub role: DeviceRole,
103 pub away: bool,
105 pub heads: Vec<ChangeId>,
107 pub damaged: u64,
110 pub unrepaired: u64,
113 pub waits: u64,
117}
118
119#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct BackupHead {
125 pub disk: Hash,
127 pub away: bool,
129 pub heads: Vec<ChangeId>,
131 pub damaged: u64,
133 pub unrepaired: u64,
135 pub update: u64,
137 pub waits: u64,
140}
141
142#[derive(Clone, Debug, PartialEq, Eq)]
144pub enum PageBody {
145 Head(Head),
147 BackupHead(BackupHead),
149 Blobs(u8, Vec<(Hash, u64)>),
153 Copies(u8, Vec<(EntityId, Hash, u64)>),
158}
159
160impl PageBody {
161 #[must_use]
163 pub fn kind(&self) -> PageKind {
164 match self {
165 Self::Head(_) | Self::BackupHead(_) => PageKind::Head,
166 Self::Blobs(byte, _) => PageKind::Blobs(*byte),
167 Self::Copies(byte, _) => PageKind::Copies(*byte),
168 }
169 }
170
171 fn to_cbor(&self) -> Value {
172 match self {
173 Self::Head(head) => Value::Array(vec![
174 head.disk.to_cbor(),
175 head.role.as_str().to_cbor(),
176 head.away.to_cbor(),
177 head.heads.to_cbor(),
178 head.damaged.to_cbor(),
179 head.unrepaired.to_cbor(),
180 head.waits.to_cbor(),
181 ]),
182 Self::BackupHead(head) => Value::Array(vec![
183 head.disk.to_cbor(),
184 head.away.to_cbor(),
185 head.heads.to_cbor(),
186 head.damaged.to_cbor(),
187 head.unrepaired.to_cbor(),
188 head.update.to_cbor(),
189 head.waits.to_cbor(),
190 ]),
191 Self::Blobs(_, blobs) => Value::Array(
192 blobs
193 .iter()
194 .map(|(sealed, checked)| {
195 Value::Array(vec![sealed.to_cbor(), checked.to_cbor()])
196 })
197 .collect(),
198 ),
199 Self::Copies(_, copies) => Value::Array(
200 copies
201 .iter()
202 .map(|(file, content, checked)| {
203 Value::Array(vec![file.to_cbor(), content.to_cbor(), checked.to_cbor()])
204 })
205 .collect(),
206 ),
207 }
208 }
209
210 fn from_cbor(kind: PageKind, backup: bool, value: &Value) -> Result<Self, LogError> {
214 let bad = |what: &'static str| LogError::Account(what);
215 let Value::Array(items) = value else {
216 return Err(bad("a page's body is no array"));
217 };
218 match kind {
219 PageKind::Head if backup => read_backup_head(items),
220 PageKind::Copies(_) if backup => Err(bad("a backup's account lists no plain copies")),
221 PageKind::Head => read_head(items),
222 PageKind::Blobs(byte) => {
223 let mut blobs = Vec::with_capacity(items.len());
224 for item in items {
225 let Value::Array(pair) = item else {
226 return Err(bad("a blob is [sealed hash, checked]"));
227 };
228 let [sealed, checked] = pair.as_slice() else {
229 return Err(bad("a blob is [sealed hash, checked]"));
230 };
231 let sealed = Hash::from_cbor(sealed).map_err(LogError::Operations)?;
232 if sealed.digest().first() != Some(&byte) {
233 return Err(bad("a blob on another page"));
234 }
235 blobs.push((
236 sealed,
237 u64::from_cbor(checked).map_err(LogError::Operations)?,
238 ));
239 }
240 if !blobs.windows(2).all(|pair| pair[0].0 < pair[1].0) {
241 return Err(bad("blobs that are not sorted once each"));
242 }
243 Ok(Self::Blobs(byte, blobs))
244 }
245 PageKind::Copies(byte) => {
246 let mut copies = Vec::with_capacity(items.len());
247 for item in items {
248 let Value::Array(triple) = item else {
249 return Err(bad("a plain copy is [file, content, checked]"));
250 };
251 let [file, content, checked] = triple.as_slice() else {
252 return Err(bad("a plain copy is [file, content, checked]"));
253 };
254 let file = EntityId::from_cbor(file).map_err(LogError::Operations)?;
255 if file.as_bytes()[0] != byte {
256 return Err(bad("a plain copy on another page"));
257 }
258 copies.push((
259 file,
260 Hash::from_cbor(content).map_err(LogError::Operations)?,
261 u64::from_cbor(checked).map_err(LogError::Operations)?,
262 ));
263 }
264 if !copies
265 .windows(2)
266 .all(|pair| (pair[0].0, pair[0].1) < (pair[1].0, pair[1].1))
267 {
268 return Err(bad("plain copies that are not sorted once each"));
269 }
270 Ok(Self::Copies(byte, copies))
271 }
272 }
273 }
274}
275
276#[derive(Clone, Debug, PartialEq, Eq)]
284pub struct AccountPage {
285 space: SpaceId,
286 epoch: u64,
287 author: VerifyingKey,
288 about: Option<EntityId>,
290 kind: PageKind,
291 issued: u64,
292 body: Envelope,
293 signature: Signature,
294}
295
296impl AccountPage {
297 #[must_use]
301 pub fn issue(
302 space: SpaceId,
303 keys: &SpaceKeys,
304 signing: &SigningKey,
305 (issued, body): (u64, &PageBody),
306 rng: &mut impl CryptoRng,
307 ) -> Self {
308 Self::issue_of(space, keys, signing, None, (issued, body), rng)
309 }
310
311 #[must_use]
314 pub fn issue_about(
315 space: SpaceId,
316 keys: &SpaceKeys,
317 signing: &SigningKey,
318 backup: EntityId,
319 (issued, body): (u64, &PageBody),
320 rng: &mut impl CryptoRng,
321 ) -> Self {
322 Self::issue_of(space, keys, signing, Some(backup), (issued, body), rng)
323 }
324
325 fn issue_of(
326 space: SpaceId,
327 keys: &SpaceKeys,
328 signing: &SigningKey,
329 about: Option<EntityId>,
330 (issued, body): (u64, &PageBody),
331 rng: &mut impl CryptoRng,
332 ) -> Self {
333 let (epoch, space_key) = keys.newest();
334 let author = signing.verifying_key();
335 let kind = body.kind();
336 let header = header(space, epoch, &author, (about, kind), issued);
337 let sealed = Envelope::seal(
338 &accounts_key(space_key),
339 &cbor::encode(&body.to_cbor()),
340 &cbor::encode(&header),
341 rng,
342 );
343 let signature = signing.sign(SIGNATURE_CONTEXT, &signed(&header, &sealed));
344 Self {
345 space,
346 epoch,
347 author,
348 about,
349 kind,
350 issued,
351 body: sealed,
352 signature,
353 }
354 }
355
356 pub fn from_bytes(bytes: &[u8]) -> Result<Self, LogError> {
364 let bad = |what: &'static str| LogError::Account(what);
365 if bytes.len() > MAX_PAGE_LEN {
366 return Err(bad("a page longer than 4 MiB"));
367 }
368 let value = cbor::decode(bytes)
369 .map_err(|error| LogError::Operations(cbor::Error::Decode(error)))?;
370 let Value::Array(items) = &value else {
371 return Err(bad("a page is [1, header, body, signature]"));
372 };
373 let [version, header, body, signature] = items.as_slice() else {
374 return Err(bad("a page is [1, header, body, signature]"));
375 };
376 if u64::from_cbor(version).ok() != Some(VERSION) {
377 return Err(bad("a page of another version"));
378 }
379 let Value::Array(fields) = header else {
380 return Err(bad("a header is [space, epoch, author, page, issued]"));
381 };
382 let [space, epoch, author, kind, issued] = fields.as_slice() else {
383 return Err(bad("a header is [space, epoch, author, page, issued]"));
384 };
385 let operations = LogError::Operations;
386 let (about, number) = match kind {
389 Value::Array(pair) => {
390 let [backup, number] = pair.as_slice() else {
391 return Err(bad("a backup's page is [backup, number]"));
392 };
393 (
394 Some(EntityId::from_cbor(backup).map_err(operations)?),
395 number,
396 )
397 }
398 number => (None, number),
399 };
400 let kind = PageKind::from_number(u64::from_cbor(number).map_err(operations)?)
401 .ok_or(bad("a page that is none of an account's"))?;
402 if about.is_some() && matches!(kind, PageKind::Copies(_)) {
403 return Err(bad("a backup's account lists no plain copies"));
404 }
405 let page = Self {
406 space: SpaceId::from_cbor(space).map_err(operations)?,
407 epoch: u64::from_cbor(epoch).map_err(operations)?,
408 author: VerifyingKey::from_cbor(author).map_err(operations)?,
409 about,
410 kind,
411 issued: u64::from_cbor(issued).map_err(operations)?,
412 body: Envelope::from_cbor(body).map_err(operations)?,
413 signature: Signature::from_cbor(signature).map_err(operations)?,
414 };
415 page.author
416 .verify(
417 SIGNATURE_CONTEXT,
418 &signed(header, &page.body),
419 &page.signature,
420 )
421 .map_err(|_| LogError::InvalidSignature)?;
422 Ok(page)
423 }
424
425 #[must_use]
427 pub fn to_bytes(&self) -> Vec<u8> {
428 cbor::encode(&Value::Array(vec![
429 VERSION.to_cbor(),
430 self.header(),
431 self.body.to_cbor(),
432 self.signature.to_cbor(),
433 ]))
434 }
435
436 #[must_use]
438 pub fn id(&self) -> Hash {
439 Hash::of(&self.to_bytes())
440 }
441
442 pub fn open(&self, keys: &SpaceKeys) -> Result<PageBody, LogError> {
450 let space_key = keys
451 .get(self.epoch)
452 .ok_or(LogError::UnknownEpoch(self.epoch))?;
453 let plaintext = self
454 .body
455 .open(&accounts_key(space_key), &cbor::encode(&self.header()))
456 .map_err(|_| LogError::Decryption)?;
457 let value = cbor::decode(&plaintext)
458 .map_err(|error| LogError::Operations(cbor::Error::Decode(error)))?;
459 PageBody::from_cbor(self.kind, self.about.is_some(), &value)
460 }
461
462 #[must_use]
464 pub const fn space(&self) -> SpaceId {
465 self.space
466 }
467
468 #[must_use]
470 pub const fn author(&self) -> &VerifyingKey {
471 &self.author
472 }
473
474 #[must_use]
476 pub const fn kind(&self) -> PageKind {
477 self.kind
478 }
479
480 #[must_use]
482 pub const fn about(&self) -> Option<EntityId> {
483 self.about
484 }
485
486 #[must_use]
488 pub const fn issued(&self) -> u64 {
489 self.issued
490 }
491
492 #[must_use]
494 pub const fn epoch(&self) -> u64 {
495 self.epoch
496 }
497
498 fn header(&self) -> Value {
499 header(
500 self.space,
501 self.epoch,
502 &self.author,
503 (self.about, self.kind),
504 self.issued,
505 )
506 }
507}
508
509fn header(
510 space: SpaceId,
511 epoch: u64,
512 author: &VerifyingKey,
513 (about, kind): (Option<EntityId>, PageKind),
514 issued: u64,
515) -> Value {
516 let page = match about {
517 None => kind.number().to_cbor(),
518 Some(backup) => Value::Array(vec![backup.to_cbor(), kind.number().to_cbor()]),
519 };
520 Value::Array(vec![
521 space.to_cbor(),
522 epoch.to_cbor(),
523 author.to_cbor(),
524 page,
525 issued.to_cbor(),
526 ])
527}
528
529fn signed(header: &Value, body: &Envelope) -> Vec<u8> {
531 cbor::encode(&Value::Array(vec![header.clone(), body.to_cbor()]))
532}
533
534fn accounts_key(space_key: &Key) -> Key {
536 space_key.derive(ACCOUNTS_CONTEXT)
537}
538
539fn read_head(items: &[Value]) -> Result<PageBody, LogError> {
541 let bad = |what: &'static str| LogError::Account(what);
542 let [disk, role, away, heads, damaged, unrepaired, waits] = items else {
543 return Err(bad(
544 "a head page is [disk, role, away, heads, damaged, unrepaired, waits]",
545 ));
546 };
547 let role = DeviceRole::from_name(&String::from_cbor(role).map_err(LogError::Operations)?)
548 .ok_or(bad("a role that is neither everyday nor archive"))?;
549 let heads = Vec::<ChangeId>::from_cbor(heads).map_err(LogError::Operations)?;
550 if !heads.windows(2).all(|pair| pair[0] < pair[1]) {
551 return Err(bad("heads that are not sorted once each"));
552 }
553 Ok(PageBody::Head(Head {
554 disk: Hash::from_cbor(disk).map_err(LogError::Operations)?,
555 role,
556 away: bool::from_cbor(away).map_err(LogError::Operations)?,
557 heads,
558 damaged: u64::from_cbor(damaged).map_err(LogError::Operations)?,
559 unrepaired: u64::from_cbor(unrepaired).map_err(LogError::Operations)?,
560 waits: u64::from_cbor(waits).map_err(LogError::Operations)?,
561 }))
562}
563
564fn read_backup_head(items: &[Value]) -> Result<PageBody, LogError> {
566 let bad = |what: &'static str| LogError::Account(what);
567 let [disk, away, heads, damaged, unrepaired, update, waits] = items else {
568 return Err(bad(
569 "a backup's head page is [disk, away, heads, damaged, unrepaired, update, waits]",
570 ));
571 };
572 let heads = Vec::<ChangeId>::from_cbor(heads).map_err(LogError::Operations)?;
573 if !heads.windows(2).all(|pair| pair[0] < pair[1]) {
574 return Err(bad("heads that are not sorted once each"));
575 }
576 Ok(PageBody::BackupHead(BackupHead {
577 disk: Hash::from_cbor(disk).map_err(LogError::Operations)?,
578 away: bool::from_cbor(away).map_err(LogError::Operations)?,
579 heads,
580 damaged: u64::from_cbor(damaged).map_err(LogError::Operations)?,
581 unrepaired: u64::from_cbor(unrepaired).map_err(LogError::Operations)?,
582 update: u64::from_cbor(update).map_err(LogError::Operations)?,
583 waits: u64::from_cbor(waits).map_err(LogError::Operations)?,
584 }))
585}
586
587#[cfg(test)]
588mod tests {
589 use nibkeep_testkit::TestRng;
590
591 use super::*;
592
593 fn keys(rng: &mut TestRng) -> SpaceKeys {
594 SpaceKeys::new(0, Key::generate(rng))
595 }
596
597 fn head() -> PageBody {
598 let mut heads = vec![
599 ChangeId::from_hash(Hash::of(b"a")),
600 ChangeId::from_hash(Hash::of(b"b")),
601 ];
602 heads.sort();
603 PageBody::Head(Head {
604 disk: Hash::of(b"disk"),
605 role: DeviceRole::Archive,
606 away: true,
607 heads,
608 damaged: 2,
609 unrepaired: 1,
610 waits: 30,
611 })
612 }
613
614 #[test]
615 fn a_page_reads_as_it_was_issued_and_opens_with_the_space_key() {
616 let mut rng = TestRng::new("account pages");
617 let keys = keys(&mut rng);
618 let signing = SigningKey::generate(&mut rng);
619 let space = SpaceId::random(&mut rng);
620 let body = head();
621 let page = AccountPage::issue(space, &keys, &signing, (1_000, &body), &mut rng);
622 let read = AccountPage::from_bytes(&page.to_bytes()).expect("reads");
623 assert_eq!(read, page);
624 assert_eq!(read.to_bytes(), page.to_bytes());
625 assert_eq!(read.author(), &signing.verifying_key());
626 assert_eq!(
627 (read.kind(), read.issued(), read.space()),
628 (PageKind::Head, 1_000, space)
629 );
630 assert_eq!(read.open(&keys).expect("opens"), body);
631 assert!(matches!(
633 read.open(&SpaceKeys::new(0, Key::generate(&mut rng))),
634 Err(LogError::Decryption)
635 ));
636 }
637
638 #[test]
639 fn a_head_page_without_its_wait_does_not_read() {
640 let items = [
641 Hash::of(b"disk").to_cbor(),
642 "archive".to_owned().to_cbor(),
643 true.to_cbor(),
644 Vec::<ChangeId>::new().to_cbor(),
645 2_u64.to_cbor(),
646 1_u64.to_cbor(),
647 30_u64.to_cbor(),
648 ];
649 assert!(read_head(&items).is_ok());
650 assert!(matches!(read_head(&items[..6]), Err(LogError::Account(_))));
651 let backup = [
652 Hash::of(b"disk").to_cbor(),
653 true.to_cbor(),
654 Vec::<ChangeId>::new().to_cbor(),
655 2_u64.to_cbor(),
656 1_u64.to_cbor(),
657 4_u64.to_cbor(),
658 30_u64.to_cbor(),
659 ];
660 assert!(read_backup_head(&backup).is_ok());
661 assert!(matches!(
662 read_backup_head(&backup[..6]),
663 Err(LogError::Account(_))
664 ));
665 }
666
667 #[test]
668 fn a_page_that_another_key_signed_or_that_was_changed_is_refused() {
669 let mut rng = TestRng::new("forged account pages");
670 let keys = keys(&mut rng);
671 let signing = SigningKey::generate(&mut rng);
672 let space = SpaceId::random(&mut rng);
673 let body = PageBody::Blobs(7, Vec::new());
674 let page = AccountPage::issue(space, &keys, &signing, (5, &body), &mut rng);
675 let mut forged = page.clone();
677 forged.author = SigningKey::generate(&mut rng).verifying_key();
678 assert!(matches!(
679 AccountPage::from_bytes(&forged.to_bytes()),
680 Err(LogError::InvalidSignature)
681 ));
682 let mut later = page;
683 later.issued = 6;
684 assert!(matches!(
685 AccountPage::from_bytes(&later.to_bytes()),
686 Err(LogError::InvalidSignature)
687 ));
688 }
689
690 #[test]
691 fn entries_on_the_wrong_page_or_out_of_order_do_not_open() {
692 let mut rng = TestRng::new("account entries");
693 let keys = keys(&mut rng);
694 let signing = SigningKey::generate(&mut rng);
695 let space = SpaceId::random(&mut rng);
696 let sealed = Hash::of(b"a blob");
697 let byte = sealed.digest()[0];
698 let fine = PageBody::Blobs(byte, vec![(sealed, 3)]);
699 let page = AccountPage::issue(space, &keys, &signing, (1, &fine), &mut rng);
700 assert_eq!(page.open(&keys).expect("opens"), fine);
701 let elsewhere = PageBody::Blobs(byte.wrapping_add(1), vec![(sealed, 3)]);
702 let page = AccountPage::issue(space, &keys, &signing, (1, &elsewhere), &mut rng);
703 assert!(matches!(page.open(&keys), Err(LogError::Account(_))));
704 let twice = PageBody::Blobs(byte, vec![(sealed, 3), (sealed, 4)]);
705 let page = AccountPage::issue(space, &keys, &signing, (1, &twice), &mut rng);
706 assert!(matches!(page.open(&keys), Err(LogError::Account(_))));
707 }
708
709 #[test]
710 fn plain_copies_tell_when_each_was_checked_and_are_listed_once() {
711 let mut rng = TestRng::new("account copies");
712 let keys = keys(&mut rng);
713 let signing = SigningKey::generate(&mut rng);
714 let space = SpaceId::random(&mut rng);
715 let file = EntityId::from_bytes([3; 16]);
716 let mut contents = [Hash::of(b"a film"), Hash::of(b"its new version")];
717 contents.sort();
718 let listed = PageBody::Copies(3, vec![(file, contents[0], 7), (file, contents[1], 0)]);
719 let page = AccountPage::issue(space, &keys, &signing, (1, &listed), &mut rng);
720 let read = AccountPage::from_bytes(&page.to_bytes()).expect("reads");
721 assert_eq!(read.open(&keys).expect("opens"), listed);
722 let twice = PageBody::Copies(3, vec![(file, contents[0], 7), (file, contents[0], 9)]);
724 let page = AccountPage::issue(space, &keys, &signing, (1, &twice), &mut rng);
725 assert!(matches!(page.open(&keys), Err(LogError::Account(_))));
726 }
727
728 #[test]
729 fn a_page_about_a_backup_reads_with_its_backup_and_update() {
730 let mut rng = TestRng::new("backup pages");
731 let keys = keys(&mut rng);
732 let signing = SigningKey::generate(&mut rng);
733 let space = SpaceId::random(&mut rng);
734 let backup = EntityId::from_bytes([9; 16]);
735 let body = PageBody::BackupHead(BackupHead {
736 disk: Hash::of(b"stick"),
737 away: true,
738 heads: vec![ChangeId::from_hash(Hash::of(b"a"))],
739 damaged: 1,
740 unrepaired: 0,
741 update: 12,
742 waits: 14,
743 });
744 let page = AccountPage::issue_about(space, &keys, &signing, backup, (7, &body), &mut rng);
745 let read = AccountPage::from_bytes(&page.to_bytes()).expect("reads");
746 assert_eq!(read, page);
747 assert_eq!((read.about(), read.kind()), (Some(backup), PageKind::Head));
748 assert_eq!(read.open(&keys).expect("opens"), body);
749 let own = AccountPage::issue_about(space, &keys, &signing, backup, (8, &head()), &mut rng);
751 assert!(own.open(&keys).is_err());
752 let swapped = AccountPage::issue(space, &keys, &signing, (9, &body), &mut rng);
753 assert!(swapped.open(&keys).is_err());
754 }
755
756 #[test]
757 fn page_numbers_name_each_page_once() {
758 for kind in [
759 PageKind::Head,
760 PageKind::Blobs(0),
761 PageKind::Blobs(255),
762 PageKind::Copies(9),
763 ] {
764 assert_eq!(PageKind::from_number(u64::from(kind.number())), Some(kind));
765 }
766 assert_eq!(PageKind::from_number(1), None);
767 assert_eq!(PageKind::from_number(0x300), None);
768 }
769}