1use sha2::{Digest, Sha384};
11
12use crate::crypto::network::digest::sha384;
13use crate::crypto::network::errors::CryptoError;
14
15pub const MAX_FLIGHT_BYTES: usize = 16 * 1024;
17pub const MAX_CHUNKS_PER_FLIGHT: usize = 16;
19pub const MAX_GLOBAL_PENDING: usize = 32;
21pub const MAX_PER_LOCATOR: usize = 2;
23
24#[repr(C)]
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct ChunkFlight {
28 pub locator: u64,
29 pub expiry_unix: u64,
30 pub chunk_count: u8,
31 pub byte_len: u16,
32 pub digest: [u8; 48],
34}
35
36struct FlightSlot {
37 meta: ChunkFlight,
38 chunk_digests: [Option<[u8; 48]>; MAX_CHUNKS_PER_FLIGHT],
39 chunk_lens: [u16; MAX_CHUNKS_PER_FLIGHT],
40 hasher: Sha384,
41}
42
43pub struct ChunkTable {
45 slots: [Option<FlightSlot>; MAX_GLOBAL_PENDING],
46}
47
48impl ChunkTable {
49 pub const fn new() -> Self {
51 Self {
52 slots: [
53 None, None, None, None, None, None, None, None, None, None, None, None, None, None,
54 None, None, None, None, None, None, None, None, None, None, None, None, None, None,
55 None, None, None, None,
56 ],
57 }
58 }
59
60 pub fn open(&mut self, locator: u64, now_unix: u64, ttl_secs: u64) -> Result<u8, CryptoError> {
62 let mut per_locator = 0usize;
63 let mut i = 0usize;
64 while i < MAX_GLOBAL_PENDING {
65 if let Some(slot) = &self.slots[i] {
66 if slot.meta.locator == locator {
67 per_locator += 1;
68 if per_locator >= MAX_PER_LOCATOR {
69 return Err(CryptoError::Capacity);
70 }
71 }
72 }
73 i += 1;
74 }
75 let mut i = 0usize;
76 while i < MAX_GLOBAL_PENDING {
77 if self.slots[i].is_none() {
78 let hasher = Sha384::new();
79 let empty = sha384(&[]);
80 self.slots[i] = Some(FlightSlot {
81 meta: ChunkFlight {
82 locator,
83 expiry_unix: now_unix.saturating_add(ttl_secs),
84 chunk_count: 0,
85 byte_len: 0,
86 digest: empty.0,
87 },
88 chunk_digests: [None; MAX_CHUNKS_PER_FLIGHT],
89 chunk_lens: [0u16; MAX_CHUNKS_PER_FLIGHT],
90 hasher,
91 });
92 return Ok(i as u8);
93 }
94 i += 1;
95 }
96 Err(CryptoError::Capacity)
97 }
98
99 pub fn append(
103 &mut self,
104 flight: u8,
105 index: u8,
106 bytes: &[u8],
107 now_unix: u64,
108 ) -> Result<(), CryptoError> {
109 let slot = self.slot_mut(flight)?;
110 if now_unix > slot.meta.expiry_unix {
111 return Err(CryptoError::Expired);
112 }
113 let idx = index as usize;
114 if idx >= MAX_CHUNKS_PER_FLIGHT {
115 return Err(CryptoError::Capacity);
116 }
117 let incoming = chunk_id(bytes);
118 if let Some(stored) = slot.chunk_digests[idx] {
119 if stored == incoming {
120 return Err(CryptoError::Replay);
121 }
122 return Err(CryptoError::Conflict);
123 }
124 if idx != slot.meta.chunk_count as usize {
125 return Err(CryptoError::Range);
126 }
127 if (slot.meta.byte_len as usize).saturating_add(bytes.len()) > MAX_FLIGHT_BYTES {
128 return Err(CryptoError::Capacity);
129 }
130 let stored_len: u16 = bytes.len().try_into().map_err(|_| CryptoError::Capacity)?;
131 slot.hasher.update(bytes);
132 let out = slot.hasher.clone().finalize();
133 slot.meta.digest.copy_from_slice(&out);
134 slot.chunk_digests[idx] = Some(incoming);
135 slot.chunk_lens[idx] = stored_len;
136 slot.meta.byte_len = slot.meta.byte_len.saturating_add(stored_len);
137 slot.meta.chunk_count = slot.meta.chunk_count.saturating_add(1);
138 Ok(())
139 }
140
141 pub fn expiry(&self, flight: u8) -> Result<u64, CryptoError> {
143 Ok(self.slot(flight)?.meta.expiry_unix)
144 }
145
146 fn slot(&self, flight: u8) -> Result<&FlightSlot, CryptoError> {
147 let i = flight as usize;
148 if i >= MAX_GLOBAL_PENDING {
149 return Err(CryptoError::Range);
150 }
151 self.slots[i].as_ref().ok_or(CryptoError::Range)
152 }
153
154 fn slot_mut(&mut self, flight: u8) -> Result<&mut FlightSlot, CryptoError> {
155 let i = flight as usize;
156 if i >= MAX_GLOBAL_PENDING {
157 return Err(CryptoError::Range);
158 }
159 self.slots[i].as_mut().ok_or(CryptoError::Range)
160 }
161}
162
163pub fn duplicate_extends_deadline() -> bool {
165 false
166}
167
168fn chunk_id(bytes: &[u8]) -> [u8; 48] {
169 sha384(bytes).0
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 #[test]
177 fn open_thirty_two_ok_thirty_third_capacity() {
178 let mut table = ChunkTable::new();
179 let mut i = 0u64;
180 while i < MAX_GLOBAL_PENDING as u64 {
181 assert_eq!(table.open(i + 1, 1, 10), Ok(i as u8));
182 i += 1;
183 }
184 assert_eq!(table.open(99, 1, 10), Err(CryptoError::Capacity));
185 }
186
187 #[test]
188 fn third_open_same_locator_capacity() {
189 let mut table = ChunkTable::new();
190 assert_eq!(table.open(7, 1, 10), Ok(0));
191 assert_eq!(table.open(7, 1, 10), Ok(1));
192 assert_eq!(table.open(7, 1, 10), Err(CryptoError::Capacity));
193 assert_eq!(table.open(8, 1, 10), Ok(2));
194 }
195
196 #[test]
197 fn sixteen_chunks_ok_seventeenth_capacity() {
198 let mut table = ChunkTable::new();
199 let flight = table.open(1, 1, 10).unwrap();
200 let mut i = 0u8;
201 while i < MAX_CHUNKS_PER_FLIGHT as u8 {
202 let b = [i; 1];
203 assert_eq!(table.append(flight, i, &b, 1), Ok(()));
204 i += 1;
205 }
206 assert_eq!(
207 table.append(flight, MAX_CHUNKS_PER_FLIGHT as u8, b"x", 1),
208 Err(CryptoError::Capacity)
209 );
210 }
211
212 #[test]
213 fn byte_len_over_sixteen_kib_capacity() {
214 let mut table = ChunkTable::new();
215 let flight = table.open(1, 1, 10).unwrap();
216 let oversized = [0u8; MAX_FLIGHT_BYTES + 1];
217 assert_eq!(
218 table.append(flight, 0, &oversized, 1),
219 Err(CryptoError::Capacity)
220 );
221
222 let mut table = ChunkTable::new();
223 let flight = table.open(2, 1, 10).unwrap();
224 let piece = [1u8; 1025];
225 let mut i = 0u8;
226 while i < 15 {
227 assert_eq!(table.append(flight, i, &piece, 1), Ok(()));
228 i += 1;
229 }
230 assert_eq!(
231 table.append(flight, 15, &piece, 1),
232 Err(CryptoError::Capacity)
233 );
234 }
235
236 #[test]
237 fn duplicate_same_index_same_digest_is_replay_expiry_unchanged() {
238 let mut table = ChunkTable::new();
239 let flight = table.open(1, 1000, 100).unwrap();
240 assert_eq!(table.append(flight, 0, b"same", 1000), Ok(()));
241 let before = table.expiry(flight).unwrap();
242 assert_eq!(
243 table.append(flight, 0, b"same", 1000),
244 Err(CryptoError::Replay)
245 );
246 assert_eq!(table.expiry(flight).unwrap(), before);
247 assert!(!duplicate_extends_deadline());
248 }
249
250 #[test]
251 fn different_digest_same_index_is_conflict() {
252 let mut table = ChunkTable::new();
253 let flight = table.open(1, 1, 10).unwrap();
254 assert_eq!(table.append(flight, 0, b"one", 1), Ok(()));
255 assert_eq!(
256 table.append(flight, 0, b"two", 1),
257 Err(CryptoError::Conflict)
258 );
259 }
260
261 #[test]
262 fn duplicate_extends_deadline_is_false() {
263 assert!(!duplicate_extends_deadline());
264 }
265
266 #[test]
267 fn append_after_expiry_is_expired() {
268 let mut table = ChunkTable::new();
269 let flight = table.open(1, 100, 5).unwrap();
270 assert_eq!(table.expiry(flight).unwrap(), 105);
271 assert_eq!(
272 table.append(flight, 0, b"late", 106),
273 Err(CryptoError::Expired)
274 );
275 assert_eq!(table.append(flight, 0, b"ok", 105), Ok(()));
276 }
277
278 #[test]
279 fn ordered_flight_digest_is_sha384_of_concatenated_bytes() {
280 let mut table = ChunkTable::new();
281 let flight = table.open(1, 1, 10).unwrap();
282 assert_eq!(table.append(flight, 0, b"aa", 1), Ok(()));
283 assert_eq!(table.append(flight, 1, b"bb", 1), Ok(()));
284 let expect = sha384(b"aabb");
285 let slot = table.slot(flight).unwrap();
286 assert_eq!(slot.meta.digest, expect.0);
287 assert_eq!(slot.meta.chunk_count, 2);
288 assert_eq!(slot.meta.byte_len, 4);
289 assert_eq!(slot.chunk_lens[0], 2);
290 assert_eq!(slot.chunk_lens[1], 2);
291 }
292}