Skip to main content

nibkeep_node/library/
verify.rs

1//! Checking a library: its log files and its blobs, and the files kept where they are.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6use nibkeep_base::{EntityId, Hash, SpaceId};
7use nibkeep_log::ChangeId;
8use nibkeep_model::{Value, fields};
9use nibkeep_std::{CONTENT, FILE};
10use nibkeep_store::{SealedCheck, StoreError, StoredLog};
11
12use super::export::blake3_of;
13use super::{Library, policies};
14use crate::NodeError;
15
16/// What checking a library found.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct Report {
19	/// Each space, the personal space first.
20	pub spaces: Vec<SpaceReport>,
21}
22
23/// What checking a space found.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct SpaceReport {
26	/// The space.
27	pub id: SpaceId,
28	/// Its name, if it has one.
29	pub name: Option<String>,
30	/// How many changes were checked, accepted or waiting: their signatures now, the rest
31	/// when the library was opened.
32	pub changes: usize,
33	/// How many blobs were read in full.
34	pub blobs: usize,
35	/// How many sealed files have keys that the replica cannot open yet, such as keys of a
36	/// space key it has not received, or of secret files while the secrets are locked. They
37	/// wait for their keys, and are not read.
38	pub waiting: usize,
39	/// How many files that this device keeps where they were found, and not in the store,
40	/// were read there in full and still hold their content.
41	pub in_place: usize,
42	/// The places where this device found a file it keeps only there, which no longer hold
43	/// its content, or cannot be read: changed, gone or locked away, so that they no longer
44	/// count as copies. Nothing is wrong with the library for them.
45	pub changed: Vec<PathBuf>,
46	/// What is wrong, if anything.
47	pub problems: Vec<Problem>,
48}
49
50/// Something wrong with a space.
51#[derive(Clone, Debug, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum Problem {
54	/// SQLite's check of the log file found it damaged, or could not run.
55	Database(String),
56	/// A stored change's signature is not valid: the log file was damaged or tampered
57	/// with. Opening the library trusts the signatures checked when changes arrived.
58	ForgedChange(ChangeId),
59	/// A stored change cannot be read, as the error says, such as one that this replica did
60	/// not store: the log file was damaged or tampered with.
61	DamagedChange(ChangeId, String),
62	/// The replica's copy of a blob is damaged: it is moved aside, and a sync brings it again
63	/// from a replica that holds it intact.
64	DamagedBlob(Hash),
65	/// The replica's copy of a blob is intact, but its key does not open it to its content:
66	/// the key is wrong.
67	WrongBlobKey(Hash),
68	/// The replica's copy of a blob cannot be read, as the error says.
69	UnreadableBlob(Hash, String),
70	/// Some stored keys of a sealed blob were bad, and opening the library removed them.
71	BadBlobKeys(Hash),
72	/// No key of any space of the replica opens a sealed blob, and no purge explains why:
73	/// unless another replica sends one, its content is lost. The replica's spaces share
74	/// their blob directory, so the personal space's report names these.
75	KeylessBlob(Hash),
76	/// A file in the replica's blob directory is not a sealed blob, which the personal
77	/// space's report names.
78	UnknownFile(PathBuf),
79	/// A check could not be finished, as the error says.
80	Unchecked(String),
81}
82
83impl Report {
84	/// How many problems checking found.
85	#[must_use]
86	pub fn problems(&self) -> usize {
87		self.spaces.iter().map(|space| space.problems.len()).sum()
88	}
89
90	/// Whether nothing is wrong.
91	#[must_use]
92	pub fn is_sound(&self) -> bool {
93		self.problems() == 0
94	}
95}
96
97impl Library {
98	/// Checks the library: SQLite's check of every log file, the signature of every
99	/// change, and every blob that the replica can read, read in full against its content
100	/// hash. The rest of every change was checked again, and bad stored keys removed, when
101	/// the library was opened; the report names the keys removed. Blobs found intact are
102	/// recorded as checked at `wall_millis`; a damaged copy is moved aside, so that a sync
103	/// brings it again, as the regular check does ([technical design: checking and repair]).
104	/// Files that this device keeps where they were found are read there and checked against
105	/// their hashes too, and those whose size and modification time are unchanged recorded as
106	/// checked. What one check cannot finish is a problem in the report, and the other checks
107	/// go on.
108	///
109	/// [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
110	///
111	/// # Errors
112	///
113	/// Returns an error if a batch of changes is open, whose changes are not saved yet, or
114	/// if the library has a space it did not open, which it never should.
115	pub fn verify(&mut self, wall_millis: u64) -> Result<Report, NodeError> {
116		if self.spaces.values().any(|open| open.stored.in_batch()) {
117			return Err(StoreError::InBatch.into());
118		}
119		let mut ids: Vec<SpaceId> = self.spaces.keys().copied().collect();
120		ids.sort_by_key(|&id| (id != self.info.personal, id));
121		// What each space explains of the blob directory that they share.
122		let mut known = BTreeMap::new();
123		for (&id, open) in &self.spaces {
124			known.insert(id, open.stored.known_blobs());
125		}
126		let mut spaces = Vec::new();
127		for id in ids {
128			let (name, unnamed) = match self.space(id)?.name(&self.languages) {
129				Ok(name) => (name, None),
130				Err(error) => (None, Some(Problem::Unchecked(error.to_string()))),
131			};
132			let open = self.spaces.get_mut(&id).ok_or(NodeError::NoSpace(id))?;
133			let mut report = SpaceReport {
134				id,
135				name,
136				changes: open.stored.log().kept()?,
137				blobs: 0,
138				waiting: 0,
139				in_place: 0,
140				changed: Vec::new(),
141				problems: unnamed.into_iter().collect(),
142			};
143			// Without what another space explains, the files that no space explains are not
144			// told apart; the space's own checks go on.
145			let mut elsewhere = BTreeSet::new();
146			let mut strays = id == self.info.personal;
147			for (_, other) in known.iter().filter(|(other, _)| **other != id) {
148				match other {
149					Ok(other) => elsewhere.extend(other),
150					Err(error) => {
151						if strays {
152							report.problems.push(Problem::Unchecked(error.to_string()));
153						}
154						strays = false;
155					}
156				}
157			}
158			check_space(
159				&mut open.stored,
160				(&elsewhere, strays),
161				wall_millis,
162				&mut report,
163			);
164			let open = self.spaces.get_mut(&id).ok_or(NodeError::NoSpace(id))?;
165			let read = check_in_place(&open.stored, self.info.device, &mut report);
166			// Every unchanged plain copy is recorded as checked, held or not, those read
167			// above without reading them again.
168			if let Err(error) = self.check_plain_now(id, &read, wall_millis) {
169				report.problems.push(Problem::Unchecked(error.to_string()));
170			}
171			spaces.push(report);
172		}
173		// What was moved aside is recorded in every space that keeps a key for it.
174		self.note_aside(wall_millis);
175		Ok(Report { spaces })
176	}
177}
178
179/// Checks a space's log file and blobs. The sealed hashes that the replica's other spaces
180/// explain are `elsewhere`; the files that no space explains, and those that are no sealed
181/// blobs, are named only where `strays` says, as all spaces share the blob directory.
182fn check_space(
183	stored: &mut StoredLog,
184	(elsewhere, strays): (&BTreeSet<Hash>, bool),
185	wall_millis: u64,
186	report: &mut SpaceReport,
187) {
188	match stored.integrity_problems() {
189		Ok(found) => report
190			.problems
191			.extend(found.into_iter().map(Problem::Database)),
192		Err(error) => report.problems.push(Problem::Database(error.to_string())),
193	}
194	match stored.log().forged() {
195		Ok(forged) => report
196			.problems
197			.extend(forged.into_iter().map(|(id, unreadable)| match unreadable {
198				None => Problem::ForgedChange(id),
199				Some(error) => Problem::DamagedChange(id, error.to_string()),
200			})),
201		Err(error) => report.problems.push(Problem::Unchecked(error.to_string())),
202	}
203	report.problems.extend(
204		stored
205			.blob_keys_dropped_at_open()
206			.iter()
207			.copied()
208			.map(Problem::BadBlobKeys),
209	);
210	let inventory = match stored.blob_inventory(elsewhere) {
211		Ok(inventory) => inventory,
212		Err(error) => {
213			report.problems.push(Problem::Unchecked(error.to_string()));
214			return;
215		}
216	};
217	report.waiting = inventory.waiting;
218	if strays {
219		report
220			.problems
221			.extend(inventory.keyless.into_iter().map(Problem::KeylessBlob));
222		report
223			.problems
224			.extend(inventory.unknown.into_iter().map(Problem::UnknownFile));
225	}
226	let mut damaged = BTreeSet::new();
227	for content in inventory.held {
228		report.blobs += 1;
229		match stored.verify_blob(&content, wall_millis) {
230			Ok(()) => {}
231			Err(StoreError::DamagedBlob) => {
232				damaged.insert(content);
233				report.problems.push(damaged_or_wrong_key(stored, &content));
234			}
235			Err(error @ (StoreError::Io(_) | StoreError::MissingBlob)) => report
236				.problems
237				.push(Problem::UnreadableBlob(content, error.to_string())),
238			Err(error) => {
239				report.problems.push(Problem::Unchecked(error.to_string()));
240				return;
241			}
242		}
243	}
244	// The copies kept aside, moved by an earlier check or by this one in another space,
245	// that still read damaged: each one put back, as intact after all, is no problem.
246	for sealed in stored.aside_blobs() {
247		let content = stored.log().content_of_sealed(&sealed).unwrap_or(sealed);
248		if damaged.contains(&content) {
249			continue;
250		}
251		match stored.recheck_aside_blob(&sealed, &|| false) {
252			Ok(SealedCheck::Intact(_) | SealedCheck::Gone) => {}
253			Ok(_) => {
254				damaged.insert(content);
255				report.problems.push(Problem::DamagedBlob(content));
256			}
257			Err(error) => report
258				.problems
259				.push(Problem::UnreadableBlob(content, error.to_string())),
260		}
261	}
262}
263
264/// What a copy of `content` that did not open to its content is: damaged, where a copy's
265/// bytes differ from its sealed hash, which it then moves aside; held under a wrong key,
266/// where every copy's bytes are intact; or else unreadable, as when a copy could not be read
267/// again or moved.
268fn damaged_or_wrong_key(stored: &StoredLog, content: &Hash) -> Problem {
269	let sealed: Vec<Hash> = stored
270		.log()
271		.blob_keys(content)
272		.map(|(sealed, _)| *sealed)
273		.filter(|sealed| stored.holds_sealed(sealed))
274		.collect();
275	let mut moved = false;
276	let mut failed = None;
277	for each in sealed {
278		match stored.check_sealed_blob(&each, &|| false) {
279			Ok(SealedCheck::Damaged) => match stored.set_aside_blob(&each) {
280				Ok(true) => moved = true,
281				Ok(false) => {}
282				Err(error) => {
283					failed = Some(format!("damaged, but it could not be moved aside: {error}"));
284				}
285			},
286			Ok(_) => {}
287			Err(error) => failed = Some(error.to_string()),
288		}
289	}
290	match (moved, failed) {
291		(true, _) => Problem::DamagedBlob(*content),
292		(false, Some(failed)) => Problem::UnreadableBlob(*content, failed),
293		(false, None) => Problem::WrongBlobKey(*content),
294	}
295}
296
297/// Checks the files of a space that this device keeps only where it found them: reads each
298/// place on `device` that an origin names, and tells whether it still holds the content.
299/// Returns the hash of each place it read.
300fn check_in_place(
301	stored: &StoredLog,
302	device: EntityId,
303	report: &mut SpaceReport,
304) -> BTreeMap<String, Hash> {
305	let mut read = BTreeMap::new();
306	let files = match stored.find(&fields::TYPE, &Value::Text(FILE.to_string())) {
307		Ok(files) => files,
308		Err(error) => {
309			report.problems.push(Problem::Unchecked(error.to_string()));
310			return read;
311		}
312	};
313	let mut checked = BTreeSet::new();
314	for file in files {
315		match kept_in_place(stored, device, file, &mut checked) {
316			Ok(Some((content, places))) => {
317				let mut held = false;
318				for place in places {
319					let found = blake3_of(Path::new(&place));
320					if found.as_ref().is_ok_and(|found| *found == content) {
321						held = true;
322					} else {
323						report.changed.push(PathBuf::from(&place));
324					}
325					if let Ok(found) = found {
326						read.insert(place, found);
327					}
328				}
329				report.in_place += usize::from(held);
330			}
331			Ok(None) => {}
332			Err(error) => {
333				report.problems.push(Problem::Unchecked(error.to_string()));
334				return read;
335			}
336		}
337	}
338	read
339}
340
341/// The content of a file that this device, `device`, keeps only where it found it, and the
342/// places there, unless the file is deleted, its content is in the store, or it was checked
343/// already, as `checked` notes.
344fn kept_in_place(
345	stored: &StoredLog,
346	device: EntityId,
347	file: EntityId,
348	checked: &mut BTreeSet<EntityId>,
349) -> Result<Option<(Hash, Vec<String>)>, NodeError> {
350	let state = stored.log().state();
351	let file = state.canonical(file)?;
352	if !checked.insert(file) || state.is_deleted(file)? {
353		return Ok(None);
354	}
355	let content =
356		state
357			.current(file, &CONTENT)?
358			.iter()
359			.find_map(|statement| match statement.value {
360				Value::Blob(hash) => Some(hash),
361				_ => None,
362			});
363	let Some(content) = content.filter(|content| !stored.holds_ordinary_blob(content)) else {
364		return Ok(None);
365	};
366	let places = policies::origins_of(state, file)?
367		.into_iter()
368		.filter(|(_, on, _)| *on == device)
369		.map(|(_, _, place)| place)
370		.collect();
371	Ok(Some((content, places)))
372}