Skip to main content

qualia_core_db/net/peer/replication/
scan.rs

1//! Bounded QSync content scan (SVC-01.16 partial).
2//!
3//! Logical size is a `u64`. Admitted resident is a `u32` cap (4 MiB), never a
4//! buffer allocated to that size or to `logical_bytes`. Each page copies into a
5//! caller-owned buffer of at most [`MAX_PAGE_BYTES`]. This is not RAM-sized
6//! materialization and is not a complete QSync package.
7//!
8//! Declared limits: wire delivery is at-least-once (a [`QdnfError::Capacity`]
9//! does not advance the cursor, so the same offset may be re-offered). Local
10//! application of `Ok(n > 0)` is at-most-once for this cursor (offset advances).
11//! Not exactly-once. Continuations do not refill remaining caps. Cancelled
12//! complete cannot resurrect.
13
14use sha2::{Digest, Sha256};
15
16use crate::net::peer::replication::source::ScanSource;
17use crate::net::peer::runtime::cancel::{CancelEpoch, OperationTable};
18use crate::net::peer::runtime::leases::LeaseTable;
19use crate::net::qdnf::errors::QdnfError;
20use crate::net::qdnf::types::{Generation, OperationId, StrongDigest};
21
22/// Maximum bytes copied into one caller page.
23pub const MAX_PAGE_BYTES: u32 = 4096;
24/// Canonical `.q42` SuperBlock byte size (853 `NQuin`s × 48 B + 16 B tail padding).
25pub const Q42_SUPERBLOCK_BYTES: usize = 40_960;
26/// Maximum 48-byte `NQuin`s stored in one `.q42` SuperBlock.
27pub const Q42_QUINS_PER_SUPERBLOCK: usize = 853;
28/// Maximum pages charged against one remaining [`ScanBudget`].
29pub const MAX_PAGES: u16 = 32;
30/// Admitted resident ceiling. Not a dataset size and not an allocated buffer.
31pub const RESIDENT_CAP_BYTES: u32 = 4 * 1024 * 1024;
32
33const PAGE_WORK: u64 = 1;
34
35/// Remaining scan quanta. Continuations must not refill these fields.
36#[repr(C)]
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct ScanBudget {
39    pub pages: u16,
40    pub work: u64,
41    pub bytes: u32,
42}
43
44impl ScanBudget {
45    pub const ZERO: Self = Self {
46        pages: 0,
47        work: 0,
48        bytes: 0,
49    };
50
51    /// Finite quantum caps. Not an unlimited scan.
52    pub const fn initial() -> Self {
53        Self {
54            pages: MAX_PAGES,
55            work: MAX_PAGES as u64,
56            bytes: MAX_PAGES as u32 * MAX_PAGE_BYTES,
57        }
58    }
59
60    #[inline]
61    /// `true` when finite.
62    pub const fn is_finite(self) -> bool {
63        self.pages <= MAX_PAGES
64    }
65}
66
67/// Copy cursor: operation id, logical offset, generation, remaining budget.
68#[repr(C)]
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub struct ScanCursor {
71    pub op: OperationId,
72    pub offset: u64,
73    pub generation: Generation,
74    pub cancel_epoch: CancelEpoch,
75    pub remaining: ScanBudget,
76    pub logical_bytes: u64,
77    pub resident_cap: u32,
78    /// ZERO means no authenticated source (synthetic `next_page` is not evidence).
79    source_digest: StrongDigest,
80    cancelled: bool,
81    /// Production scans require [`ScanSource`] via [`open_production_scan`].
82    production: bool,
83}
84
85impl ScanCursor {
86    #[inline]
87    /// `true` when cancelled.
88    pub const fn is_cancelled(self) -> bool {
89        self.cancelled
90    }
91}
92
93/// Open a scan over a logical size. Never materializes `logical_bytes`.
94///
95/// [`QdnfError::Capacity`] if `resident_cap == 0 && logical_bytes > 0`, if
96/// `resident_cap > RESIDENT_CAP_BYTES`, or if `budget.pages > MAX_PAGES`.
97pub fn open_scan(
98    logical_bytes: u64,
99    resident_cap: u32,
100    budget: ScanBudget,
101) -> Result<ScanCursor, QdnfError> {
102    if resident_cap == 0 && logical_bytes > 0 {
103        return Err(QdnfError::Capacity);
104    }
105    if resident_cap > RESIDENT_CAP_BYTES {
106        return Err(QdnfError::Capacity);
107    }
108    if !budget.is_finite() {
109        return Err(QdnfError::Capacity);
110    }
111    Ok(ScanCursor {
112        op: scan_op_id(logical_bytes, resident_cap),
113        offset: 0,
114        generation: Generation(1),
115        cancel_epoch: CancelEpoch::ZERO,
116        remaining: budget,
117        logical_bytes,
118        resident_cap,
119        source_digest: StrongDigest::ZERO,
120        cancelled: false,
121        production: false,
122    })
123}
124
125/// Open a scan bound to an authenticated source identity (not computed here).
126///
127/// [`QdnfError::Malformed`] if `source_digest` is [`StrongDigest::ZERO`].
128pub fn open_scan_bound(
129    logical_bytes: u64,
130    resident_cap: u32,
131    budget: ScanBudget,
132    source_digest: StrongDigest,
133) -> Result<ScanCursor, QdnfError> {
134    if source_digest == StrongDigest::ZERO {
135        return Err(QdnfError::Malformed);
136    }
137    let mut cursor = open_scan(logical_bytes, resident_cap, budget)?;
138    cursor.source_digest = source_digest;
139    Ok(cursor)
140}
141
142/// Open a production scan bound to `source`. Requires a non-zero source digest.
143///
144/// Uses [`ScanSource::logical_len`]. Production pages must be copied with
145/// [`next_page_from`]; the synthetic XOR [`next_page`] is [`QdnfError::Unsupported`].
146pub fn open_production_scan(
147    source: &impl ScanSource,
148    resident_cap: u32,
149    budget: ScanBudget,
150    source_digest: StrongDigest,
151) -> Result<ScanCursor, QdnfError> {
152    let mut cursor = open_scan_bound(source.logical_len(), resident_cap, budget, source_digest)?;
153    cursor.production = true;
154    Ok(cursor)
155}
156
157/// Copy the next page into `out` using the synthetic XOR fill.
158///
159/// This path is **not** storage evidence. Production scans must use
160/// [`next_page_from`] with a [`ScanSource`]. [`synthetic_scan_is_storage_evidence`]
161/// is always false. Kept for budget/cursor tests.
162///
163/// Empty `out` with remaining logical bytes is [`QdnfError::Capacity`] and
164/// does not advance offset. Exhausted remaining caps are
165/// [`QdnfError::BudgetExhausted`] and do not reset on retry.
166pub fn next_page(cursor: &mut ScanCursor, out: &mut [u8]) -> Result<usize, QdnfError> {
167    if cursor.production {
168        return Err(QdnfError::Unsupported);
169    }
170    let n = next_page_prepare(cursor, out)?;
171    if n == 0 {
172        return Ok(0);
173    }
174    fill_page(cursor.offset, &mut out[..n]);
175    commit_page(cursor, n);
176    Ok(n)
177}
178
179/// Copy the next page from `source` via [`ScanSource::read_at`] at `cursor.offset`.
180///
181/// Bytes come from the source, never the synthetic XOR fill. Budget and
182/// cursor rules match [`next_page`].
183pub fn next_page_from(
184    cursor: &mut ScanCursor,
185    source: &impl ScanSource,
186    out: &mut [u8],
187) -> Result<usize, QdnfError> {
188    let n = next_page_prepare(cursor, out)?;
189    if n == 0 {
190        return Ok(0);
191    }
192    if cursor.offset >= source.logical_len() {
193        return Err(QdnfError::Incomplete);
194    }
195    let source_remaining = source.logical_len() - cursor.offset;
196    let want = if source_remaining < n as u64 {
197        source_remaining as usize
198    } else {
199        n
200    };
201    if want == 0 {
202        return Err(QdnfError::Incomplete);
203    }
204    let got = source.read_at(cursor.offset, &mut out[..want])?;
205    if got == 0 {
206        return Err(QdnfError::Incomplete);
207    }
208    commit_page(cursor, got);
209    Ok(got)
210}
211
212/// Stop further pages. A cancelled cursor cannot resume as if cancel never
213/// happened. Idempotent.
214pub fn cancel_scan(cursor: &mut ScanCursor) -> Result<(), QdnfError> {
215    if cursor.cancelled {
216        return Ok(());
217    }
218    cursor.cancel_epoch = cursor.cancel_epoch.next()?;
219    cursor.cancelled = true;
220    Ok(())
221}
222
223/// Gate further pages on [`OperationTable`] cancel. Table cancel stops pages.
224pub fn next_page_in(
225    ops: &OperationTable,
226    cursor: &mut ScanCursor,
227    out: &mut [u8],
228) -> Result<usize, QdnfError> {
229    if ops.is_cancelled(cursor.op) {
230        cursor.cancelled = true;
231        return Err(QdnfError::Cancelled);
232    }
233    next_page(cursor, out)
234}
235
236/// Cancel the cursor and the admitted operation, if present.
237pub fn cancel_scan_in(
238    ops: &mut OperationTable,
239    cursor: &mut ScanCursor,
240) -> Result<CancelEpoch, QdnfError> {
241    cancel_scan(cursor)?;
242    match ops.cancel(cursor.op) {
243        Ok(epoch) => {
244            cursor.cancel_epoch = epoch;
245            Ok(epoch)
246        }
247        Err(QdnfError::Closed) => Ok(cursor.cancel_epoch),
248        Err(e) => Err(e),
249    }
250}
251
252/// Admit a page-sized exclusive lease (never `logical_bytes`) for this scan.
253pub fn admit_scan(
254    ops: &mut OperationTable,
255    leases: &mut LeaseTable,
256    cursor: &mut ScanCursor,
257) -> Result<(), QdnfError> {
258    if cursor.cancelled {
259        return Err(QdnfError::Cancelled);
260    }
261    let lease = leases.acquire(MAX_PAGE_BYTES, true)?;
262    match ops.admit(cursor.op, lease.handle) {
263        Ok(handle) => {
264            cursor.generation = handle.generation;
265            cursor.cancel_epoch = handle.cancel_epoch;
266            Ok(())
267        }
268        Err(e) => {
269            let _ = leases.release(lease.handle);
270            Err(e)
271        }
272    }
273}
274
275/// Finish the admitted scan. After cancel this releases storage and returns
276/// [`QdnfError::Cancelled`] so a late page is not a live success.
277pub fn complete_scan(
278    ops: &mut OperationTable,
279    leases: &mut LeaseTable,
280    cursor: &mut ScanCursor,
281) -> Result<(), QdnfError> {
282    match ops.complete(cursor.op, cursor.generation, leases) {
283        Ok(()) => Ok(()),
284        Err(QdnfError::Cancelled) => {
285            cursor.cancelled = true;
286            Err(QdnfError::Cancelled)
287        }
288        Err(e) => Err(e),
289    }
290}
291
292/// Pages may be re-offered after Capacity if the cursor was not advanced.
293#[inline]
294pub fn at_least_once_delivery() -> bool {
295    true
296}
297
298/// Once `Ok(n > 0)` returns, a later `next_page` uses a higher offset.
299#[inline]
300pub fn at_most_once_local_application() -> bool {
301    true
302}
303
304/// This module never allocates or maps a RAM-sized logical dataset.
305#[inline]
306pub fn ram_sized_dataset_materialized() -> bool {
307    let _ = core::mem::size_of::<StrongDigest>();
308    false
309}
310
311/// `next_page` copies into caller-owned `out` with no `Vec`/`String`/`Box`.
312#[inline]
313pub fn allocation_class_hot_zero_heap() -> bool {
314    true
315}
316
317/// Continuations never restore pages/work/bytes.
318#[inline]
319pub fn continuation_refills_budget() -> bool {
320    false
321}
322
323/// Synthetic XOR `next_page` fill is never storage evidence.
324#[inline]
325pub fn synthetic_scan_is_storage_evidence() -> bool {
326    false
327}
328
329/// Production scans copy through [`ScanSource`], never the XOR fill.
330#[inline]
331pub fn production_scan_uses_synthetic_xor() -> bool {
332    false
333}
334
335/// True only when [`open_scan_bound`] attached a non-zero source digest.
336#[inline]
337pub fn scan_pages_are_storage_evidence(cursor: &ScanCursor) -> bool {
338    cursor.source_digest != StrongDigest::ZERO
339}
340
341/// Verify a `.q42` SuperBlock slice against its expected SHA-256 Merkle chain
342/// digest and verify canonical 5-field `NQuin` XOR parity (`s ^ p ^ o ^ c ^ m`)
343/// on every 48-byte Quin in the slice (`R08`).
344pub fn verify_superblock_slice_parity_and_sha256(
345    superblock_bytes: &[u8],
346    expected_sha256: &[u8; 32],
347) -> Result<usize, QdnfError> {
348    if superblock_bytes.is_empty() || superblock_bytes.len() > Q42_SUPERBLOCK_BYTES {
349        return Err(QdnfError::Range);
350    }
351    let mut hasher = Sha256::new();
352    hasher.update(superblock_bytes);
353    let actual_sha256 = hasher.finalize();
354    if actual_sha256.as_slice() != expected_sha256.as_slice() {
355        return Err(QdnfError::Conflict);
356    }
357
358    let max_quin_bytes = Q42_QUINS_PER_SUPERBLOCK * 48;
359    let payload_len = if superblock_bytes.len() > max_quin_bytes {
360        max_quin_bytes
361    } else {
362        superblock_bytes.len()
363    };
364    let quin_count = payload_len / 48;
365    let mut i = 0usize;
366    while i < quin_count {
367        let base = i * 48;
368        let s = u64::from_le_bytes([
369            superblock_bytes[base],
370            superblock_bytes[base + 1],
371            superblock_bytes[base + 2],
372            superblock_bytes[base + 3],
373            superblock_bytes[base + 4],
374            superblock_bytes[base + 5],
375            superblock_bytes[base + 6],
376            superblock_bytes[base + 7],
377        ]);
378        let p = u64::from_le_bytes([
379            superblock_bytes[base + 8],
380            superblock_bytes[base + 9],
381            superblock_bytes[base + 10],
382            superblock_bytes[base + 11],
383            superblock_bytes[base + 12],
384            superblock_bytes[base + 13],
385            superblock_bytes[base + 14],
386            superblock_bytes[base + 15],
387        ]);
388        let o = u64::from_le_bytes([
389            superblock_bytes[base + 16],
390            superblock_bytes[base + 17],
391            superblock_bytes[base + 18],
392            superblock_bytes[base + 19],
393            superblock_bytes[base + 20],
394            superblock_bytes[base + 21],
395            superblock_bytes[base + 22],
396            superblock_bytes[base + 23],
397        ]);
398        let c = u64::from_le_bytes([
399            superblock_bytes[base + 24],
400            superblock_bytes[base + 25],
401            superblock_bytes[base + 26],
402            superblock_bytes[base + 27],
403            superblock_bytes[base + 28],
404            superblock_bytes[base + 29],
405            superblock_bytes[base + 30],
406            superblock_bytes[base + 31],
407        ]);
408        let m = u64::from_le_bytes([
409            superblock_bytes[base + 32],
410            superblock_bytes[base + 33],
411            superblock_bytes[base + 34],
412            superblock_bytes[base + 35],
413            superblock_bytes[base + 36],
414            superblock_bytes[base + 37],
415            superblock_bytes[base + 38],
416            superblock_bytes[base + 39],
417        ]);
418        let parity = u64::from_le_bytes([
419            superblock_bytes[base + 40],
420            superblock_bytes[base + 41],
421            superblock_bytes[base + 42],
422            superblock_bytes[base + 43],
423            superblock_bytes[base + 44],
424            superblock_bytes[base + 45],
425            superblock_bytes[base + 46],
426            superblock_bytes[base + 47],
427        ]);
428        if (s ^ p ^ o ^ c ^ m) != parity {
429            return Err(QdnfError::Conflict);
430        }
431        i += 1;
432    }
433    Ok(quin_count)
434}
435
436fn next_page_prepare(cursor: &ScanCursor, out: &[u8]) -> Result<usize, QdnfError> {
437    if cursor.cancelled {
438        return Err(QdnfError::Cancelled);
439    }
440    if cursor.offset > cursor.logical_bytes {
441        return Err(QdnfError::Range);
442    }
443    let remaining_logical = cursor.logical_bytes - cursor.offset;
444    if remaining_logical == 0 {
445        return Ok(0);
446    }
447    if out.is_empty() {
448        return Err(QdnfError::Capacity);
449    }
450
451    let n = page_len(out.len(), remaining_logical);
452    if cursor.remaining.pages == 0 || cursor.remaining.work < PAGE_WORK {
453        return Err(QdnfError::BudgetExhausted);
454    }
455    if cursor.remaining.bytes < n as u32 {
456        return Err(QdnfError::BudgetExhausted);
457    }
458    Ok(n)
459}
460
461fn commit_page(cursor: &mut ScanCursor, n: usize) {
462    cursor.remaining.pages -= 1;
463    cursor.remaining.work -= PAGE_WORK;
464    cursor.remaining.bytes -= n as u32;
465    cursor.offset += n as u64;
466}
467
468fn scan_op_id(logical_bytes: u64, resident_cap: u32) -> OperationId {
469    let mut id = [0u8; 16];
470    id[0..8].copy_from_slice(&logical_bytes.to_le_bytes());
471    id[8..12].copy_from_slice(&resident_cap.to_le_bytes());
472    id[12] = 0x51;
473    OperationId(id)
474}
475
476fn page_len(out_len: usize, remaining_logical: u64) -> usize {
477    let cap = if out_len > MAX_PAGE_BYTES as usize {
478        MAX_PAGE_BYTES as usize
479    } else {
480        out_len
481    };
482    if remaining_logical > cap as u64 {
483        cap
484    } else {
485        remaining_logical as usize
486    }
487}
488
489fn fill_page(offset: u64, out: &mut [u8]) {
490    let mut i = 0usize;
491    while i < out.len() {
492        let pos = offset.wrapping_add(i as u64);
493        out[i] = (pos as u8) ^ ((pos >> 8) as u8) ^ ((pos >> 16) as u8);
494        i += 1;
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use crate::net::peer::runtime::leases::LEASE_SLOTS;
502
503    const EIGHT_GIB: u64 = 8 * 1024 * 1024 * 1024;
504
505    fn open_large() -> ScanCursor {
506        open_scan(EIGHT_GIB, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap()
507    }
508
509    #[test]
510    fn larger_than_ram_open_pages_without_materializing() {
511        let mut cursor = open_large();
512        assert!(cursor.logical_bytes > cursor.resident_cap as u64);
513        let mut page = [0u8; MAX_PAGE_BYTES as usize];
514        let n = next_page(&mut cursor, &mut page).unwrap();
515        assert!(n > 0);
516        assert!(n <= MAX_PAGE_BYTES as usize);
517        assert!(!ram_sized_dataset_materialized());
518        assert!(allocation_class_hot_zero_heap());
519    }
520
521    #[test]
522    fn thirty_third_page_is_budget_exhausted_and_continuation_does_not_refill() {
523        let mut cursor = open_large();
524        let mut page = [0u8; MAX_PAGE_BYTES as usize];
525        let mut i = 0u16;
526        while i < MAX_PAGES {
527            let n = next_page(&mut cursor, &mut page).unwrap();
528            assert_eq!(n, MAX_PAGE_BYTES as usize);
529            i += 1;
530        }
531        assert_eq!(cursor.remaining.pages, 0);
532        assert_eq!(
533            next_page(&mut cursor, &mut page),
534            Err(QdnfError::BudgetExhausted)
535        );
536        assert!(!continuation_refills_budget());
537        assert_eq!(cursor.remaining.pages, 0);
538        assert_eq!(
539            next_page(&mut cursor, &mut page),
540            Err(QdnfError::BudgetExhausted)
541        );
542        assert_eq!(cursor.remaining.pages, 0);
543    }
544
545    #[test]
546    fn cancel_then_next_page_is_cancelled() {
547        let mut cursor = open_large();
548        cancel_scan(&mut cursor).unwrap();
549        let mut page = [0u8; MAX_PAGE_BYTES as usize];
550        assert_eq!(next_page(&mut cursor, &mut page), Err(QdnfError::Cancelled));
551        assert_eq!(next_page(&mut cursor, &mut page), Err(QdnfError::Cancelled));
552    }
553
554    #[test]
555    fn capacity_on_empty_out_does_not_advance_offset() {
556        let mut cursor = open_large();
557        let start = cursor.offset;
558        assert_eq!(next_page(&mut cursor, &mut []), Err(QdnfError::Capacity));
559        assert_eq!(cursor.offset, start);
560        assert_eq!(cursor.remaining.pages, MAX_PAGES);
561        let mut page = [0u8; MAX_PAGE_BYTES as usize];
562        let n = next_page(&mut cursor, &mut page).unwrap();
563        assert_eq!(n, MAX_PAGE_BYTES as usize);
564        assert!(at_least_once_delivery());
565        assert_eq!(cursor.offset, start + n as u64);
566    }
567
568    #[test]
569    fn ok_page_advances_offset_at_most_once() {
570        let mut cursor = open_large();
571        let mut page = [0u8; MAX_PAGE_BYTES as usize];
572        let first = cursor.offset;
573        let n = next_page(&mut cursor, &mut page).unwrap();
574        assert!(n > 0);
575        let after = cursor.offset;
576        assert!(after > first);
577        let n2 = next_page(&mut cursor, &mut page).unwrap();
578        assert!(n2 > 0);
579        assert!(cursor.offset > after);
580        assert!(at_most_once_local_application());
581    }
582
583    #[test]
584    fn ram_sized_dataset_is_not_materialized() {
585        assert!(!ram_sized_dataset_materialized());
586        let _cursor = open_large();
587        assert!(!ram_sized_dataset_materialized());
588    }
589
590    #[test]
591    fn zero_resident_cap_with_logical_data_is_capacity() {
592        assert_eq!(
593            open_scan(1, 0, ScanBudget::initial()),
594            Err(QdnfError::Capacity)
595        );
596        assert!(open_scan(0, 0, ScanBudget::initial()).is_ok());
597    }
598
599    #[test]
600    fn cancelled_complete_cannot_resurrect() {
601        let mut leases = LeaseTable::new();
602        let mut ops = OperationTable::new();
603        let mut cursor = open_large();
604        admit_scan(&mut ops, &mut leases, &mut cursor).unwrap();
605        cancel_scan_in(&mut ops, &mut cursor).unwrap();
606        let mut page = [0u8; MAX_PAGE_BYTES as usize];
607        assert_eq!(
608            next_page_in(&ops, &mut cursor, &mut page),
609            Err(QdnfError::Cancelled)
610        );
611        assert_eq!(
612            complete_scan(&mut ops, &mut leases, &mut cursor),
613            Err(QdnfError::Cancelled)
614        );
615        assert_eq!(next_page(&mut cursor, &mut page), Err(QdnfError::Cancelled));
616        assert_eq!(
617            complete_scan(&mut ops, &mut leases, &mut cursor),
618            Err(QdnfError::Closed)
619        );
620    }
621
622    #[test]
623    fn offset_past_logical_is_range_and_end_is_ok_zero() {
624        let mut cursor = open_scan(64, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
625        let mut page = [0u8; MAX_PAGE_BYTES as usize];
626        let n = next_page(&mut cursor, &mut page).unwrap();
627        assert_eq!(n, 64);
628        assert_eq!(next_page(&mut cursor, &mut page), Ok(0));
629        cursor.offset = cursor.logical_bytes + 1;
630        assert_eq!(next_page(&mut cursor, &mut page), Err(QdnfError::Range));
631    }
632
633    #[test]
634    fn page_lease_is_not_logical_size() {
635        let mut leases = LeaseTable::new();
636        let mut ops = OperationTable::new();
637        let mut cursor = open_large();
638        admit_scan(&mut ops, &mut leases, &mut cursor).unwrap();
639        assert_eq!(leases.occupied_count(), 1);
640        assert!(EIGHT_GIB > u32::MAX as u64);
641        assert!(LEASE_SLOTS >= 32);
642        complete_scan(&mut ops, &mut leases, &mut cursor).unwrap();
643        assert_eq!(leases.occupied_count(), 0);
644    }
645
646    #[test]
647    fn synthetic_scan_is_not_storage_evidence() {
648        assert!(!synthetic_scan_is_storage_evidence());
649        let cursor = open_large();
650        assert!(!scan_pages_are_storage_evidence(&cursor));
651    }
652
653    #[test]
654    fn next_page_from_copies_source_bytes_not_xor() {
655        use crate::net::peer::replication::source::MemorySource;
656
657        let src = [0xAAu8; 64];
658        let mut cursor_xor = open_scan(64, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
659        let mut cursor_src = open_scan(64, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
660        let mut xor_page = [0u8; 64];
661        let mut src_page = [0u8; 64];
662        let n_xor = next_page(&mut cursor_xor, &mut xor_page).unwrap();
663        let n_src = next_page_from(
664            &mut cursor_src,
665            &MemorySource::from_slice(&src),
666            &mut src_page,
667        )
668        .unwrap();
669        assert_eq!(n_xor, 64);
670        assert_eq!(n_src, 64);
671        assert_eq!(&src_page[..n_src], &src[..]);
672        assert_ne!(&xor_page[..n_xor], &src[..]);
673        let mut expected_xor = [0u8; 64];
674        fill_page(0, &mut expected_xor);
675        assert_eq!(xor_page, expected_xor);
676    }
677
678    #[test]
679    fn two_sources_same_length_different_pages() {
680        use crate::net::peer::replication::source::MemorySource;
681
682        let a = [1u8; 32];
683        let b = [2u8; 32];
684        let mut ca = open_scan(32, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
685        let mut cb = open_scan(32, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
686        let mut pa = [0u8; 32];
687        let mut pb = [0u8; 32];
688        assert_eq!(
689            next_page_from(&mut ca, &MemorySource::from_slice(&a), &mut pa).unwrap(),
690            32
691        );
692        assert_eq!(
693            next_page_from(&mut cb, &MemorySource::from_slice(&b), &mut pb).unwrap(),
694            32
695        );
696        assert_eq!(pa, a);
697        assert_eq!(pb, b);
698        assert_ne!(pa, pb);
699    }
700
701    #[test]
702    fn production_scan_does_not_use_synthetic_xor() {
703        use crate::net::peer::replication::source::MemorySource;
704
705        assert!(!production_scan_uses_synthetic_xor());
706        assert!(!synthetic_scan_is_storage_evidence());
707        let src = [0x5Au8; 32];
708        let mut d = StrongDigest::ZERO;
709        d.0[0] = 0x5a;
710        let mem = MemorySource::from_slice(&src);
711        let mut cursor =
712            open_production_scan(&mem, RESIDENT_CAP_BYTES, ScanBudget::initial(), d).unwrap();
713        let mut xor_try = [0u8; 32];
714        assert_eq!(
715            next_page(&mut cursor, &mut xor_try),
716            Err(QdnfError::Unsupported)
717        );
718        let mut page = [0u8; 32];
719        let n = next_page_from(&mut cursor, &mem, &mut page).unwrap();
720        assert_eq!(n, 32);
721        assert_eq!(&page[..], &src[..]);
722        let mut expected_xor = [0u8; 32];
723        fill_page(0, &mut expected_xor);
724        assert_ne!(page, expected_xor);
725    }
726
727    #[test]
728    fn bound_source_digest_is_storage_evidence_identity() {
729        let mut d = StrongDigest::ZERO;
730        d.0[0] = 0x42;
731        let unbound = open_scan(16, RESIDENT_CAP_BYTES, ScanBudget::initial()).unwrap();
732        assert!(!scan_pages_are_storage_evidence(&unbound));
733        let bound = open_scan_bound(16, RESIDENT_CAP_BYTES, ScanBudget::initial(), d).unwrap();
734        assert!(scan_pages_are_storage_evidence(&bound));
735        assert_eq!(
736            open_scan_bound(
737                16,
738                RESIDENT_CAP_BYTES,
739                ScanBudget::initial(),
740                StrongDigest::ZERO
741            ),
742            Err(QdnfError::Malformed)
743        );
744    }
745
746    #[test]
747    fn r08_superblock_slice_verifies_sha256_and_5field_quin_parity() {
748        let mut raw = [0u8; 96];
749        // Quin 0
750        let s0 = 0x11u64;
751        let p0 = 0x22u64;
752        let o0 = 0x33u64;
753        let c0 = 0x44u64;
754        let m0 = 0x55u64;
755        let par0 = s0 ^ p0 ^ o0 ^ c0 ^ m0;
756        raw[0..8].copy_from_slice(&s0.to_le_bytes());
757        raw[8..16].copy_from_slice(&p0.to_le_bytes());
758        raw[16..24].copy_from_slice(&o0.to_le_bytes());
759        raw[24..32].copy_from_slice(&c0.to_le_bytes());
760        raw[32..40].copy_from_slice(&m0.to_le_bytes());
761        raw[40..48].copy_from_slice(&par0.to_le_bytes());
762        // Quin 1 (all zeros is parity-valid)
763        let mut hasher = Sha256::new();
764        hasher.update(&raw);
765        let mut sha = [0u8; 32];
766        sha.copy_from_slice(&hasher.finalize());
767
768        assert_eq!(
769            verify_superblock_slice_parity_and_sha256(&raw, &sha),
770            Ok(2)
771        );
772
773        // Corrupt parity of Quin 1 and recompute SHA-256 -> parity check must fail closed
774        raw[88] = 1;
775        let mut hasher2 = Sha256::new();
776        hasher2.update(&raw);
777        let mut sha2 = [0u8; 32];
778        sha2.copy_from_slice(&hasher2.finalize());
779        assert_eq!(
780            verify_superblock_slice_parity_and_sha256(&raw, &sha2),
781            Err(QdnfError::Conflict)
782        );
783    }
784}