Skip to main content

nibkeep_sync/
proof.rs

1//! Proving that a replica holds a sealed blob now, before another removes its own copy: the
2//! remover sends a fresh random key and a few random ranges of the sealed bytes, and the
3//! prover answers with the BLAKE3 hash of those ranges keyed with that key, which the remover
4//! checks against its own copy ([Sync](../../../docs/spec/sync.md#3-syncing)). A plain
5//! challenge asks the same of the content itself, which the device that holds an original
6//! where it was found reads from that file, and the remover from its sealed copy, opened.
7
8use std::io;
9
10use nibkeep_base::Hash;
11use nibkeep_crypto::rand_core::CryptoRng;
12
13/// How many ranges a challenge reads of a blob larger than they take together.
14pub const RANGES: usize = 8;
15
16/// How many bytes each range of a challenge takes, but in a blob smaller than all of them.
17pub const RANGE_LEN: u32 = 1024;
18
19/// How many ranges a challenge may name at most, as the prover reads them: those that a
20/// remover draws.
21pub const MOST_RANGES: usize = RANGES;
22
23/// How many bytes a range may take at most: the whole of a blob that a remover reads in one
24/// range, so that a prover reads at most 64 KiB for each challenge.
25pub const MOST_RANGE_LEN: u32 = 8 * RANGE_LEN;
26
27const _: () = assert!(MOST_RANGE_LEN as usize == RANGES * RANGE_LEN as usize);
28
29/// How many challenges one message carries at most.
30pub const CHALLENGES_AT_ONCE: usize = 1024;
31
32/// The context of a proof's hash, which goes into it before the ranges.
33const CONTEXT: &[u8] = b"nibkeep 2026-11 proof of a sealed blob";
34
35/// The context of a plain proof's hash: of a content's own bytes.
36const PLAIN_CONTEXT: &[u8] = b"nibkeep 2026-11 proof of a plain copy";
37
38/// A range of a sealed blob's bytes: where it starts, and how many bytes it takes.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Range {
41	/// Its first byte's offset.
42	pub offset: u64,
43	/// How many bytes it takes, at least 1.
44	pub len: u32,
45}
46
47/// What a remover asks a prover to answer of a sealed blob, or of a content's own bytes.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Challenge {
50	/// The sealed blob's sealed hash, or for a plain challenge the content's hash.
51	pub sealed: Hash,
52	/// The key of the hash, fresh for each challenge.
53	pub key: [u8; 32],
54	/// The ranges of the bytes to hash, in order.
55	pub ranges: Vec<Range>,
56	/// Whether it asks for the content's own bytes, as an original holds them, rather than
57	/// a sealed blob's.
58	pub plain: bool,
59}
60
61impl Challenge {
62	/// A challenge of a sealed blob of `size` bytes: a fresh key, and [`RANGES`] random
63	/// ranges of [`RANGE_LEN`] bytes, in order of their offsets, or the whole blob if it is
64	/// no larger than those take.
65	#[must_use]
66	pub fn random(sealed: Hash, size: u64, rng: &mut (impl CryptoRng + ?Sized)) -> Self {
67		Self::drawn(sealed, size, false, rng)
68	}
69
70	/// A plain challenge of a content of `len` bytes, as [`Challenge::random`] draws one.
71	#[must_use]
72	pub fn random_plain(content: Hash, len: u64, rng: &mut (impl CryptoRng + ?Sized)) -> Self {
73		Self::drawn(content, len, true, rng)
74	}
75
76	fn drawn(sealed: Hash, size: u64, plain: bool, rng: &mut (impl CryptoRng + ?Sized)) -> Self {
77		let mut key = [0; 32];
78		rng.fill_bytes(&mut key);
79		let all = RANGES as u64 * u64::from(RANGE_LEN);
80		let ranges = if size == 0 && plain {
81			// An empty content has no bytes to read, and its hash alone is asked for.
82			Vec::new()
83		} else if size <= all {
84			// A sealed blob is never empty: its header comes first.
85			vec![Range {
86				offset: 0,
87				len: u32::try_from(size.max(1)).unwrap_or(RANGE_LEN),
88			}]
89		} else {
90			let room = size - u64::from(RANGE_LEN) + 1;
91			let mut offsets: Vec<u64> = (0..RANGES)
92				.map(|_| {
93					let mut bytes = [0; 8];
94					rng.fill_bytes(&mut bytes);
95					u64::from_le_bytes(bytes) % room
96				})
97				.collect();
98			offsets.sort_unstable();
99			offsets
100				.into_iter()
101				.map(|offset| Range {
102					offset,
103					len: RANGE_LEN,
104				})
105				.collect()
106		};
107		Self {
108			sealed,
109			key,
110			ranges,
111			plain,
112		}
113	}
114
115	/// Whether a prover reads it: no more than [`MOST_RANGES`] ranges, each of 1 to
116	/// [`MOST_RANGE_LEN`] bytes, none ending past the largest offset; none only for a plain
117	/// challenge, of an empty content.
118	#[must_use]
119	pub fn is_fair(&self) -> bool {
120		(self.plain || !self.ranges.is_empty())
121			&& self.ranges.len() <= MOST_RANGES
122			&& self.ranges.iter().all(|range| {
123				range.len >= 1
124					&& range.len <= MOST_RANGE_LEN
125					&& range.offset.checked_add(u64::from(range.len)).is_some()
126			})
127	}
128
129	/// The answer to the challenge, from the bytes as `read` reads each range, into a buffer
130	/// of the range's length: the BLAKE3 hash, keyed with the challenge's key, of the context,
131	/// which a plain challenge's differs from, the hash it names, and each range's offset,
132	/// length and bytes.
133	///
134	/// # Errors
135	///
136	/// Returns what `read` returns, as when the blob ends before a range does.
137	pub fn answer(
138		&self,
139		mut read: impl FnMut(u64, &mut [u8]) -> io::Result<()>,
140	) -> io::Result<[u8; 32]> {
141		let mut hasher = blake3::Hasher::new_keyed(&self.key);
142		hasher.update(if self.plain { PLAIN_CONTEXT } else { CONTEXT });
143		hasher.update(&self.sealed.to_multihash());
144		let mut buffer = Vec::new();
145		for range in &self.ranges {
146			buffer.resize(range.len as usize, 0);
147			read(range.offset, &mut buffer)?;
148			hasher.update(&range.offset.to_be_bytes());
149			hasher.update(&range.len.to_be_bytes());
150			hasher.update(&buffer);
151		}
152		Ok(*hasher.finalize().as_bytes())
153	}
154
155	/// The answer from the blob's bytes in memory, or `None` if a range ends past them.
156	#[must_use]
157	pub fn answer_from(&self, bytes: &[u8]) -> Option<[u8; 32]> {
158		self.answer(|offset, out| {
159			let start = usize::try_from(offset).map_err(io::Error::other)?;
160			let found = start
161				.checked_add(out.len())
162				.and_then(|end| bytes.get(start..end))
163				.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
164			out.copy_from_slice(found);
165			Ok(())
166		})
167		.ok()
168	}
169}
170
171#[cfg(test)]
172mod tests {
173	use nibkeep_testkit::TestRng;
174
175	use super::*;
176
177	#[test]
178	fn a_large_blob_is_read_in_a_few_ranges_and_a_small_one_whole() {
179		let mut rng = TestRng::new("ranges");
180		let sealed = Hash::of(b"sealed");
181		let large = Challenge::random(sealed, 10_000_000, &mut rng);
182		assert_eq!(large.ranges.len(), RANGES);
183		assert!(large.is_fair());
184		assert!(
185			large
186				.ranges
187				.windows(2)
188				.all(|pair| pair[0].offset <= pair[1].offset)
189		);
190		assert!(
191			large
192				.ranges
193				.iter()
194				.all(|range| range.offset + u64::from(range.len) <= 10_000_000)
195		);
196		let small = Challenge::random(sealed, 5_000, &mut rng);
197		assert_eq!(
198			small.ranges,
199			vec![Range {
200				offset: 0,
201				len: 5_000
202			}]
203		);
204	}
205
206	#[test]
207	fn only_the_same_bytes_answer_a_challenge() {
208		let mut rng = TestRng::new("answers");
209		let bytes: Vec<u8> = (0..100_000_u32).map(|index| (index % 251) as u8).collect();
210		let challenge = Challenge::random(Hash::of(&bytes), bytes.len() as u64, &mut rng);
211		let answer = challenge.answer_from(&bytes).expect("answers");
212		assert_eq!(challenge.answer_from(&bytes), Some(answer));
213		// Another key gives another answer, so an answer cannot be kept for later.
214		let other = Challenge::random(Hash::of(&bytes), bytes.len() as u64, &mut rng);
215		assert_ne!(other.answer_from(&bytes), Some(answer));
216		// A byte changed in a range changes it; a blob that is cut short answers nothing.
217		let mut changed = bytes.clone();
218		let at = usize::try_from(challenge.ranges[3].offset).expect("small") + 10;
219		changed[at] ^= 1;
220		assert_ne!(challenge.answer_from(&changed), Some(answer));
221		let last = challenge.ranges.last().expect("ranges");
222		let cut = usize::try_from(last.offset).expect("small");
223		assert_eq!(challenge.answer_from(&bytes[..cut]), None);
224	}
225
226	#[test]
227	fn a_plain_answer_is_not_a_sealed_one() {
228		let mut rng = TestRng::new("plain");
229		let bytes: Vec<u8> = (0..30_000_u32).map(|index| (index % 249) as u8).collect();
230		let plain = Challenge::random_plain(Hash::of(&bytes), bytes.len() as u64, &mut rng);
231		assert!(plain.plain);
232		let sealed = Challenge {
233			plain: false,
234			..plain.clone()
235		};
236		assert_ne!(plain.answer_from(&bytes), sealed.answer_from(&bytes));
237		// An empty content is asked for by its hash alone.
238		let empty = Challenge::random_plain(Hash::of(b""), 0, &mut rng);
239		assert!(empty.ranges.is_empty() && empty.is_fair());
240		assert!(empty.answer_from(&[]).is_some());
241	}
242}