1use std::io;
9
10use nibkeep_base::Hash;
11use nibkeep_crypto::rand_core::CryptoRng;
12
13pub const RANGES: usize = 8;
15
16pub const RANGE_LEN: u32 = 1024;
18
19pub const MOST_RANGES: usize = RANGES;
22
23pub const MOST_RANGE_LEN: u32 = 8 * RANGE_LEN;
26
27const _: () = assert!(MOST_RANGE_LEN as usize == RANGES * RANGE_LEN as usize);
28
29pub const CHALLENGES_AT_ONCE: usize = 1024;
31
32const CONTEXT: &[u8] = b"nibkeep 2026-11 proof of a sealed blob";
34
35const PLAIN_CONTEXT: &[u8] = b"nibkeep 2026-11 proof of a plain copy";
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Range {
41 pub offset: u64,
43 pub len: u32,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Challenge {
50 pub sealed: Hash,
52 pub key: [u8; 32],
54 pub ranges: Vec<Range>,
56 pub plain: bool,
59}
60
61impl Challenge {
62 #[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 #[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 Vec::new()
83 } else if size <= all {
84 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 #[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 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 #[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 let other = Challenge::random(Hash::of(&bytes), bytes.len() as u64, &mut rng);
215 assert_ne!(other.answer_from(&bytes), Some(answer));
216 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 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}