Skip to main content

nibkeep_log/
account.rs

1//! Accounts of copies: what each replica of a space holds, which it tells the others in
2//! pages that it signs and seals with the space key, and that they pass on
3//! ([Log](../../../docs/spec/log.md#11-accounts-of-copies)).
4
5use 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
12/// The context of the key, derived from a space key, that seals the pages of accounts.
13const ACCOUNTS_CONTEXT: &str = "nibkeep 2026-11 accounts";
14
15/// The context of a page's signature.
16const SIGNATURE_CONTEXT: &str = "nibkeep account";
17
18/// The version of the format of pages.
19const VERSION: u64 = 1;
20
21/// How long a page may be, 4 MiB: a page of blobs of a space of ten million blobs takes about
22/// half of it, and longer pages are refused, so that no replica fills another's disk with
23/// them.
24pub const MAX_PAGE_LEN: usize = 4 * 1024 * 1024;
25
26/// Which page of an account a page is: the one with the disk, the marks and the heads, or
27/// one of the pages of the sealed blobs or of the plain copies, by the first byte of the
28/// sealed hashes' digests or of the files' IDs that it lists.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub enum PageKind {
31	/// The disk, the device's marks, and the heads.
32	Head,
33	/// The sealed blobs whose sealed hash's digest starts with this byte.
34	Blobs(u8),
35	/// The plain copies of the files whose ID starts with this byte.
36	Copies(u8),
37}
38
39impl PageKind {
40	/// Its number: 0 for the head, 256 plus the byte for blobs, 512 plus the byte for plain
41	/// copies.
42	#[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	/// The kind of page that a number names, if any.
52	#[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/// What a device does with the files of its spaces, as its user marked it
64/// ([technical design](../../../docs/Technical-design.md#96-where-the-copies-are)).
65#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum DeviceRole {
67	/// An everyday device, such as a phone or a laptop: every device that is not marked.
68	#[default]
69	Everyday,
70	/// An archive node, such as a NAS or a desktop, which keeps what policies assign it.
71	Archive,
72}
73
74impl DeviceRole {
75	/// Its name, as text: `everyday` or `archive`.
76	#[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	/// The role that a name names, if any.
85	#[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/// The head of an account: the disk, its device's marks, the space's changes it holds, and
96/// what the replica's checks found damaged.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Head {
99	/// The disk's ID in the space.
100	pub disk: Hash,
101	/// Its device's role.
102	pub role: DeviceRole,
103	/// Whether its device is kept away from home.
104	pub away: bool,
105	/// The replica's heads: the space's changes it holds are these and what they build on.
106	pub heads: Vec<ChangeId>,
107	/// How many of its copies of the space's files its checks found damaged in the last 4
108	/// weeks.
109	pub damaged: u64,
110	/// How many of its copies that checks found damaged are damaged still: sealed blobs that
111	/// wait for an intact copy, and originals that do not hold their content.
112	pub unrepaired: u64,
113	/// How many days its device waits before it destroys what a purge destroys, as the wait
114	/// in force when the page was issued: 0 for none
115	/// ([technical design](../../../docs/Technical-design.md#911-copies-that-wait)).
116	pub waits: u64,
117}
118
119/// The head of the account of a backup, which a replica that updated it issues: the
120/// backup's disk, its mark, the space's changes it holds, what checks found damaged, and the
121/// number of the update that the page tells of
122/// ([technical design](../../../docs/Technical-design.md#910-backups)).
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct BackupHead {
125	/// The backup's disk's ID in the space.
126	pub disk: Hash,
127	/// Whether it is kept away from home.
128	pub away: bool,
129	/// The heads of the space's changes it holds.
130	pub heads: Vec<ChangeId>,
131	/// How many of its copies checks found damaged in the 4 weeks before the update.
132	pub damaged: u64,
133	/// How many of those it holds no intact copy of yet.
134	pub unrepaired: u64,
135	/// The number of the update.
136	pub update: u64,
137	/// How many days it waits before it destroys what a purge destroys, after the update that
138	/// first brings the purge: 0 for none.
139	pub waits: u64,
140}
141
142/// What a page tells.
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub enum PageBody {
145	/// The head of the account.
146	Head(Head),
147	/// The head of the account of a backup.
148	BackupHead(BackupHead),
149	/// The sealed blobs whose sealed hash's digest starts with the byte, each with when the
150	/// replica last read it in full and found it intact, in milliseconds since 1970, or 0
151	/// if it never did; sorted by sealed hash.
152	Blobs(u8, Vec<(Hash, u64)>),
153	/// The plain copies, on the replica's device and unchanged, of the files whose ID starts
154	/// with the byte: each file, the content the copy holds, and when the replica last read a
155	/// copy of it in full and found the content, in milliseconds since 1970, or 0 if it never
156	/// did; sorted by file and content.
157	Copies(u8, Vec<(EntityId, Hash, u64)>),
158}
159
160impl PageBody {
161	/// The kind of page it is.
162	#[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	/// Reads the body of a page of the kind given, of a backup's account if `backup` says
211	/// so, checking that what it lists is sorted, once each, and on the page that its first
212	/// byte names.
213	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/// One page of a replica's account of what it holds in a space, signed by the replica and
277/// sealed with a space key.
278///
279/// In CBOR, a page is `[1, header, body, signature]`, where the header is `[space, epoch,
280/// author, page, issued]` and the body an envelope ([`Envelope`]) sealed with the key derived
281/// from the space key of `epoch`, with the header's encoding as associated data; the
282/// signature signs the encoding of `[header, body]`.
283#[derive(Clone, Debug, PartialEq, Eq)]
284pub struct AccountPage {
285	space: SpaceId,
286	epoch: u64,
287	author: VerifyingKey,
288	/// The backup whose account it is a page of, if it is not the author's own.
289	about: Option<EntityId>,
290	kind: PageKind,
291	issued: u64,
292	body: Envelope,
293	signature: Signature,
294}
295
296impl AccountPage {
297	/// Issues a page of the account of `signing`'s replica in `space`, telling `body`,
298	/// sealed with the space key that new changes are wrapped with, and issued at `issued`,
299	/// in milliseconds since 1970.
300	#[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	/// Issues a page of the account of a backup in `space`, which `signing`'s replica
312	/// updated, as [`AccountPage::issue`] issues one of its own.
313	#[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	/// Reads a page from its encoding, and checks its signature: one that does not read, is
357	/// longer than [`MAX_PAGE_LEN`], or whose author did not sign it, is refused.
358	///
359	/// # Errors
360	///
361	/// Returns [`LogError::Account`] or [`LogError::Operations`] if the bytes are not a
362	/// page, and [`LogError::InvalidSignature`] if its signature does not check.
363	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		// A page of the author's own account names it by its number, and one of a backup's
387		// by the backup and its number.
388		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	/// Its encoding, as it is stored and sent.
426	#[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	/// The BLAKE3 hash of its encoding, by which reconciliation knows it.
437	#[must_use]
438	pub fn id(&self) -> Hash {
439		Hash::of(&self.to_bytes())
440	}
441
442	/// Opens what the page tells, with the space key it was sealed with.
443	///
444	/// # Errors
445	///
446	/// Returns [`LogError::UnknownEpoch`] if `keys` lack that key, [`LogError::Decryption`]
447	/// if the body does not open, and [`LogError::Account`] or [`LogError::Operations`] if
448	/// what it holds does not read.
449	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	/// The space whose account it is a page of.
463	#[must_use]
464	pub const fn space(&self) -> SpaceId {
465		self.space
466	}
467
468	/// The verifying key of the replica that issued it.
469	#[must_use]
470	pub const fn author(&self) -> &VerifyingKey {
471		&self.author
472	}
473
474	/// Which page it is.
475	#[must_use]
476	pub const fn kind(&self) -> PageKind {
477		self.kind
478	}
479
480	/// The backup whose account it is a page of, if it is not its author's own.
481	#[must_use]
482	pub const fn about(&self) -> Option<EntityId> {
483		self.about
484	}
485
486	/// When it was issued, in milliseconds since 1970.
487	#[must_use]
488	pub const fn issued(&self) -> u64 {
489		self.issued
490	}
491
492	/// The number of the space key that seals it.
493	#[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
529/// What a page's signature signs: the encoding of `[header, body]`.
530fn signed(header: &Value, body: &Envelope) -> Vec<u8> {
531	cbor::encode(&Value::Array(vec![header.clone(), body.to_cbor()]))
532}
533
534/// The key that seals pages, derived from a space key.
535fn accounts_key(space_key: &Key) -> Key {
536	space_key.derive(ACCOUNTS_CONTEXT)
537}
538
539/// Reads a replica's head page.
540fn 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
564/// Reads a backup's head page.
565fn 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		// Without the space key, nothing of it opens.
632		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		// Another author named, or another time, breaks the signature.
676		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		// One file and content listed twice, with two times, is refused.
723		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		// The replica's own head, put on a backup's page, does not open, nor the other way.
750		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}