1use crate::crypto::network::digest::sha384;
8use crate::net::qdnf::authority::ObservationQuality;
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::types::{Generation, StrongDigest};
11use crate::wal_intent::{bind_exact_object, ArtifactKind, IntentTable, TxId};
12
13use super::classes::{ClassifiedEvidence, EvidenceClass};
14use crate::crypto::network::types::{AEAD_NONCE_LEN, AEAD_TAG_LEN};
15
16pub const MAX_EVIDENCE: usize = 8;
17pub const MAX_ORIGINAL: usize = 256;
18pub const MAX_HOLDS: usize = 8;
19
20#[repr(C)]
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct AuthorityAtTime {
23 pub writer_id: u64,
24 pub generation: Generation,
25 pub unix_secs: u64,
26}
27
28#[repr(C)]
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct CustodyBind {
31 pub from: StrongDigest,
32 pub to: StrongDigest,
33}
34
35#[repr(C)]
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct EvidenceRecord {
38 pub class: EvidenceClass,
39 pub label_digest: StrongDigest,
40 pub original_digest: StrongDigest,
41 pub byte_len: u16,
42 pub authority: AuthorityAtTime,
43 pub order_index: u64,
44 pub uncertainty: ObservationQuality,
45 pub custody: CustodyBind,
46 pub context_digest: StrongDigest,
47 pub has_context: bool,
48}
49
50impl EvidenceRecord {
51 pub const EMPTY: Self = Self {
52 class: EvidenceClass::EphemeralDiagnostic,
53 label_digest: StrongDigest::ZERO,
54 original_digest: StrongDigest::ZERO,
55 byte_len: 0,
56 authority: AuthorityAtTime {
57 writer_id: 0,
58 generation: Generation::ZERO,
59 unix_secs: 0,
60 },
61 order_index: 0,
62 uncertainty: ObservationQuality::Unknown,
63 custody: CustodyBind {
64 from: StrongDigest::ZERO,
65 to: StrongDigest::ZERO,
66 },
67 context_digest: StrongDigest::ZERO,
68 has_context: false,
69 };
70}
71
72#[derive(Clone, Copy)]
73pub(crate) struct HoldSlot {
74 pub occupied: bool,
75 pub id: StrongDigest,
76 pub evidence: StrongDigest,
77 pub owner: StrongDigest,
78 pub deadline: u64,
79 pub live: bool,
80}
81
82impl HoldSlot {
83 pub const EMPTY: Self = Self {
84 occupied: false,
85 id: StrongDigest::ZERO,
86 evidence: StrongDigest::ZERO,
87 owner: StrongDigest::ZERO,
88 deadline: 0,
89 live: false,
90 };
91}
92
93pub(crate) struct Slot {
94 pub occupied: bool,
95 pub record: EvidenceRecord,
96 pub original: [u8; MAX_ORIGINAL],
97 pub plaintext_present: bool,
98 pub sealed: bool,
99 pub ct: [u8; MAX_ORIGINAL],
100 pub nonce: [u8; AEAD_NONCE_LEN],
101 pub tag: [u8; AEAD_TAG_LEN],
102 pub wrap_epoch: u64,
103 pub original_ct_digest: StrongDigest,
104 pub renewed: bool,
105 pub renewed_ct: [u8; MAX_ORIGINAL],
106 pub renewed_nonce: [u8; AEAD_NONCE_LEN],
107 pub renewed_tag: [u8; AEAD_TAG_LEN],
108}
109
110impl Slot {
111 pub const EMPTY: Self = Self {
112 occupied: false,
113 record: EvidenceRecord::EMPTY,
114 original: [0u8; MAX_ORIGINAL],
115 plaintext_present: false,
116 sealed: false,
117 ct: [0u8; MAX_ORIGINAL],
118 nonce: [0u8; AEAD_NONCE_LEN],
119 tag: [0u8; AEAD_TAG_LEN],
120 wrap_epoch: 0,
121 original_ct_digest: StrongDigest::ZERO,
122 renewed: false,
123 renewed_ct: [0u8; MAX_ORIGINAL],
124 renewed_nonce: [0u8; AEAD_NONCE_LEN],
125 renewed_tag: [0u8; AEAD_TAG_LEN],
126 };
127}
128
129pub struct EvidenceStore {
131 pub(crate) slots: [Slot; MAX_EVIDENCE],
132 pub(crate) holds: [HoldSlot; MAX_HOLDS],
133 pub(crate) last_clock: u64,
134 pub(crate) storage_available: bool,
135}
136
137impl EvidenceStore {
138 pub fn new() -> Self {
140 Self {
141 slots: core::array::from_fn(|_| Slot::EMPTY),
142 holds: core::array::from_fn(|_| HoldSlot::EMPTY),
143 last_clock: 0,
144 storage_available: true,
145 }
146 }
147
148 pub fn set_storage_available(&mut self, available: bool) {
150 self.storage_available = available;
151 }
152
153 pub fn last_clock(&self) -> u64 {
155 self.last_clock
156 }
157
158 pub fn count(&self) -> usize {
160 let mut n = 0usize;
161 let mut i = 0usize;
162 while i < MAX_EVIDENCE {
163 if self.slots[i].occupied {
164 n += 1;
165 }
166 i += 1;
167 }
168 n
169 }
170
171 pub(crate) fn find(&self, digest: StrongDigest) -> Option<usize> {
173 let mut i = 0usize;
174 while i < MAX_EVIDENCE {
175 if self.slots[i].occupied && self.slots[i].record.original_digest == digest {
176 return Some(i);
177 }
178 i += 1;
179 }
180 None
181 }
182
183 pub(crate) fn find_free(&self) -> Option<usize> {
185 let mut i = 0usize;
186 while i < MAX_EVIDENCE {
187 if !self.slots[i].occupied {
188 return Some(i);
189 }
190 i += 1;
191 }
192 None
193 }
194
195 pub fn record(&self, digest: StrongDigest) -> Option<&EvidenceRecord> {
197 self.find(digest).map(|i| &self.slots[i].record)
198 }
199}
200
201pub fn hash_preserves_content() -> bool {
203 false
204}
205
206pub(crate) fn admit_clock(store: &mut EvidenceStore, now: u64) -> Result<(), QdnfError> {
208 if now == 0 {
209 return Err(QdnfError::Conflict);
210 }
211 if store.last_clock != 0 && now < store.last_clock {
212 return Err(QdnfError::Expired);
213 }
214 store.last_clock = now;
215 Ok(())
216}
217
218pub fn promote(
220 store: &mut EvidenceStore,
221 intents: &mut IntentTable,
222 tx: TxId,
223 classified: ClassifiedEvidence,
224 original: &[u8],
225 authority: AuthorityAtTime,
226 order_index: u64,
227 uncertainty: ObservationQuality,
228 custody: CustodyBind,
229 context_digest: Option<StrongDigest>,
230 source_expires_at: u64,
231 now: u64,
232 original_out: &mut [u8],
233) -> Result<EvidenceRecord, QdnfError> {
234 admit_clock(store, now)?;
235 if authority.generation.0 == 0 || authority.unix_secs == 0 {
236 return Err(QdnfError::Unauthorized);
237 }
238 if now >= source_expires_at {
239 return Err(QdnfError::Expired);
240 }
241 if original.is_empty() {
242 return Err(QdnfError::Malformed);
243 }
244 if original.len() > MAX_ORIGINAL {
245 return Err(QdnfError::Capacity);
246 }
247 if custody.from.is_zero() || custody.to.is_zero() {
248 return Err(QdnfError::Incomplete);
249 }
250 if classified.class.requires_context() && context_digest.is_none() {
251 return Err(QdnfError::Incomplete);
252 }
253 if classified.label_digest.is_zero() {
254 return Err(QdnfError::Malformed);
255 }
256 let object = bind_exact_object(ArtifactKind::Evidence, original, original_out)?;
257 if object.digest != sha384(original) {
258 return Err(QdnfError::Conflict);
259 }
260 if &original_out[..original.len()] != original {
261 return Err(QdnfError::Conflict);
262 }
263 if store.find(object.digest).is_some() {
264 return Err(QdnfError::Conflict);
265 }
266 intents.stage_intent(tx, object, authority.writer_id, authority.generation)?;
267 if !store.storage_available || store.find_free().is_none() {
268 let _ = intents.abort(tx, authority.generation);
269 return Err(QdnfError::Incomplete);
270 }
271 let idx = store.find_free().ok_or(QdnfError::Incomplete)?;
272 let mut slot = Slot::EMPTY;
273 slot.occupied = true;
274 slot.plaintext_present = true;
275 slot.record = EvidenceRecord {
276 class: classified.class,
277 label_digest: classified.label_digest,
278 original_digest: object.digest,
279 byte_len: object.byte_len,
280 authority,
281 order_index,
282 uncertainty,
283 custody,
284 context_digest: context_digest.unwrap_or(StrongDigest::ZERO),
285 has_context: context_digest.is_some(),
286 };
287 slot.original[..original.len()].copy_from_slice(original);
288 store.slots[idx] = slot;
289 if let Err(e) = intents.commit(tx, authority.generation) {
290 store.slots[idx] = Slot::EMPTY;
291 return Err(e);
292 }
293 Ok(store.slots[idx].record)
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use crate::crypto::network::digest::sha384;
300 use crate::net::qdnf::policy_labels::{
301 encode_label_into, verify_label, Confidentiality, LabelFields,
302 };
303 use crate::wal_intent::IntentTable;
304
305 fn tx(n: u8) -> TxId {
306 let mut bytes = [0u8; 16];
307 bytes[15] = n;
308 TxId { bytes }
309 }
310
311 fn label() -> ClassifiedEvidence {
312 let issuer = sha384(b"e19-issuer");
313 let mut fields = LabelFields::request(Confidentiality::C1Private, issuer);
314 fields.purpose_count = 1;
315 fields.purposes[0] = sha384(b"purpose");
316 let mut buf = [0u8; 256];
317 let n = encode_label_into(&fields, &mut buf).unwrap();
318 let v = verify_label(fields, &buf[..n]).unwrap();
319 crate::net::qdnf::evidence::classes::classify(EvidenceClass::SelectedIncident, &v).unwrap()
320 }
321
322 fn auth(now: u64) -> AuthorityAtTime {
323 AuthorityAtTime {
324 writer_id: 7,
325 generation: Generation(1),
326 unix_secs: now,
327 }
328 }
329
330 fn custody() -> CustodyBind {
331 CustodyBind {
332 from: sha384(b"from"),
333 to: sha384(b"to"),
334 }
335 }
336
337 fn run(
338 store: &mut EvidenceStore,
339 intents: &mut IntentTable,
340 n: u8,
341 bytes: &[u8],
342 now: u64,
343 ctx: Option<StrongDigest>,
344 out: &mut [u8],
345 ) -> Result<EvidenceRecord, QdnfError> {
346 promote(
347 store,
348 intents,
349 tx(n),
350 label(),
351 bytes,
352 auth(now),
353 n as u64,
354 ObservationQuality::Measured,
355 custody(),
356 ctx,
357 now.saturating_add(100),
358 now,
359 out,
360 )
361 }
362
363 #[test]
364 fn hash_only_is_not_content() {
365 assert!(!hash_preserves_content());
366 }
367
368 #[test]
369 fn copies_originals_and_digest_matches() {
370 let mut store = EvidenceStore::new();
371 let mut intents = IntentTable::new();
372 let bytes = b"incident-original";
373 let mut out = [0u8; MAX_ORIGINAL];
374 let rec = run(
375 &mut store,
376 &mut intents,
377 1,
378 bytes,
379 50,
380 Some(sha384(b"contrary")),
381 &mut out,
382 )
383 .unwrap();
384 assert_eq!(&out[..bytes.len()], bytes);
385 assert_eq!(rec.original_digest, sha384(bytes));
386 assert_eq!(rec.label_digest, label().label_digest);
387 assert!(rec.has_context);
388 assert_eq!(store.count(), 1);
389 assert_eq!(store.last_clock(), 50);
390 assert!(store.record(rec.original_digest).is_some());
391 }
392
393 #[test]
394 fn unavailable_storage_is_gap_not_empty_success() {
395 let mut store = EvidenceStore::new();
396 store.set_storage_available(false);
397 let mut intents = IntentTable::new();
398 let mut out = [0u8; MAX_ORIGINAL];
399 assert_eq!(
400 run(
401 &mut store,
402 &mut intents,
403 2,
404 b"bytes",
405 50,
406 Some(sha384(b"ctx")),
407 &mut out
408 ),
409 Err(QdnfError::Incomplete)
410 );
411 assert_eq!(store.count(), 0);
412 }
413
414 #[test]
415 fn missing_context_is_incomplete_gap() {
416 let mut store = EvidenceStore::new();
417 let mut intents = IntentTable::new();
418 let mut out = [0u8; MAX_ORIGINAL];
419 assert_eq!(
420 run(&mut store, &mut intents, 3, b"sel", 50, None, &mut out),
421 Err(QdnfError::Incomplete)
422 );
423 assert_eq!(store.count(), 0);
424 }
425
426 #[test]
427 fn unavailable_clock_is_conflict_or_expired() {
428 let mut store = EvidenceStore::new();
429 let mut intents = IntentTable::new();
430 let mut out = [0u8; MAX_ORIGINAL];
431 assert_eq!(
432 run(
433 &mut store,
434 &mut intents,
435 4,
436 b"x",
437 0,
438 Some(sha384(b"c")),
439 &mut out
440 ),
441 Err(QdnfError::Conflict)
442 );
443 run(
444 &mut store,
445 &mut intents,
446 5,
447 b"first",
448 80,
449 Some(sha384(b"c")),
450 &mut out,
451 )
452 .unwrap();
453 assert_eq!(
454 run(
455 &mut store,
456 &mut intents,
457 6,
458 b"second",
459 70,
460 Some(sha384(b"c")),
461 &mut out
462 ),
463 Err(QdnfError::Expired)
464 );
465 }
466
467 #[test]
468 fn full_store_is_gap() {
469 let mut store = EvidenceStore::new();
470 let mut intents = IntentTable::new();
471 let mut out = [0u8; MAX_ORIGINAL];
472 let mut i = 0u8;
473 while i < MAX_EVIDENCE as u8 {
474 let mut b = [b'a'; 4];
475 b[0] = i;
476 run(
477 &mut store,
478 &mut intents,
479 i + 1,
480 &b,
481 100 + i as u64,
482 Some(sha384(&[i])),
483 &mut out,
484 )
485 .unwrap();
486 i += 1;
487 }
488 assert_eq!(
489 run(
490 &mut store,
491 &mut intents,
492 0x20,
493 b"overflow",
494 200,
495 Some(sha384(b"c")),
496 &mut out
497 ),
498 Err(QdnfError::Incomplete)
499 );
500 }
501}