Skip to main content

ant_node/replication/
slice.rs

1//! BLAKE3 verified-slice possession proofs for the storage-commitment audit
2//! (ADR-0002 round 2, V2-685).
3//!
4//! The audit's round 2 used to make a challenged peer return the **complete
5//! original bytes** of the sampled chunks (up to two 4 MiB chunks per response),
6//! at 5.8 to 6.2 MB per response measured in production. What that cost the
7//! fleet per day moved with the audit *rate*, not the response size, so
8//! frequency caps could move the daily total but never the cost of an
9//! individual audit. This module replaces the response shape instead: one
10//! opened 1 KiB block is a few KB rather than a full chunk, about 427x smaller,
11//! and that holds whatever the rate does.
12//!
13//! Two axes move in opposite directions, and it is worth separating them. The
14//! *freshness* construction gets strictly stronger: the nonce now enters every
15//! block leaf, closing a preprocessing gap in the old flat `nonced_hash`. The
16//! *coverage* gets weaker: round 2 samples blocks instead of checking every
17//! byte. See "What a pass does and does not prove" below — that trade is the
18//! whole design, not a footnote to it.
19//!
20//! ## Why two chains
21//!
22//! A chunk's address is `BLAKE3(content)` (its content hash), and BLAKE3 is
23//! internally a Merkle tree over 1 KiB blocks, so a **Bao verified slice** proves
24//! that a given block is the real content at a given offset *against the address
25//! the auditor already knows* — content authenticity, for free, no full chunk.
26//! But authenticity alone is checkable from purely public data (the address is
27//! public), so a node that stores nothing could pass it by fetching the block on
28//! demand from an honest holder. To bind **possession at commitment time** the
29//! responder also commits, per leaf in round 1, a fresh **nonced block tree**:
30//! a Merkle root over the same 1 KiB blocks whose leaves are **keyed** BLAKE3
31//! hashes, `keyed_BLAKE3(key=f(nonce ‖ peer ‖ key), block_index ‖ len ‖ block)`.
32//!
33//! The nonce is fed as the BLAKE3 **key**, not a message prefix, so it mixes
34//! into every chunk compression of every block leaf: there is no
35//! nonce-independent chaining value a responder can precompute across audits.
36//! (A plain `BLAKE3(nonce ‖ … ‖ block)` prefix would leave the block's tail in a
37//! second, nonce-free BLAKE3 chunk whose CV is precomputable, letting a node
38//! store ~10.7% less than each block and still reconstruct the leaf for any
39//! fresh nonce — a smaller version of the old flat-`nonced_hash` gap.) Building
40//! the *correct* `nonced_root` therefore requires all of a chunk's bytes at
41//! round-1 commit time, and the auditor picks which block to open with fresh
42//! randomness *after* the roots are committed (cut-and-choose): a responder
43//! cannot connect a real, after-the-fact-fetched block to a garbage committed
44//! root without a preimage break.
45//!
46//! In round 2 the auditor verifies both chains over the **same** block bytes:
47//! the Bao chain against the address (authenticity) and the nonced chain against
48//! the round-1 `nonced_root` (possession). Either failing is a confirmed cheat.
49//!
50//! ## What a pass does and does not prove
51//!
52//! This is a **sampling** check, and the strength claim should be read as such.
53//! The auditor holds none of the audited bytes, so it cannot tell a correct
54//! `nonced_root` from a responder-chosen one. A peer holding a fraction `p` of a
55//! chunk's blocks can commit a root built from real leaves for the blocks it
56//! kept and arbitrary leaves for the rest, and it passes whenever every fresh
57//! draw lands on a kept block. Per audit that is roughly `p^leaves` over the
58//! 3..=5 sampled leaves; the mandatory final-block opening pins the claimed
59//! length but adds no detection, since a partial holder simply keeps the final
60//! block.
61//!
62//! So a pass means "held the sampled blocks at commit time", and repeated audits
63//! drive the probability of sustained under-storage down geometrically rather
64//! than catching it outright on the first try. The full-byte round 2 this
65//! replaces caught any missing byte of a sampled chunk with certainty — that is
66//! the difference, and it is inherent: verifying every byte means moving every
67//! byte.
68//!
69//! For `p^leaves` to describe *detection* rather than merely a pass, declining
70//! to answer must not be cheaper than answering. The responder sees the drawn
71//! blocks before it replies, so an unanswered round 2 following a valid round-1
72//! proof revokes the holder credit for the commitment under audit (see
73//! `storage_commitment_audit::round2_revokes_pinned_credit`). It stays in the
74//! graced timeout lane and costs no trust, so an honest dropped reply is
75//! harmless; what it removes is the option of holding credit while never
76//! completing a possession check.
77//!
78//! Be precise about the comparison, in both directions:
79//!
80//! - Against a node under-storing **in bulk** — the realistic case, a node
81//!   dropping data to save disk — detection is close to what the full-byte
82//!   audit gave, at roughly 1/430 of the egress (measured about 427x on a
83//!   same-network control cohort: 14.49 KB against 6.19 MB). A 990-node run
84//!   caught a 256 MB in-place corruption on the first audit that reached the
85//!   node.
86//! - Against a **fine-grained** partial deleter, one shaving a little off every
87//!   chunk, this is strictly weaker per audit than serving every byte. The
88//!   compensating lever is audit *frequency*, which is exactly what the cost
89//!   reduction buys: the old shape made frequent auditing unaffordable.
90//!
91//! If a threat model ever needs sharper per-audit detection, the knob is
92//! openings per leaf, at linear egress cost.
93
94use std::io::{Cursor, Read};
95
96use crate::ant_protocol::XorName;
97
98/// Block size for slice audits: one BLAKE3 chunk (1 KiB). A block is the unit
99/// both the Bao authenticity proof and the nonced possession tree open on.
100///
101/// Matching BLAKE3's internal 1 KiB chunk means a single opened block maps to a
102/// single BLAKE3 leaf, so the Bao proof for one block is minimal.
103pub const AUDIT_BLOCK_SIZE: u64 = 1024;
104
105/// Domain tag for a nonced block-tree leaf. Distinct from every other hash in
106/// the protocol so a leaf can never be reinterpreted as a node or a commitment.
107const DOMAIN_BLOCK_LEAF: &[u8] = b"autonomi.ant.audit.slice.block-leaf.v1";
108
109/// Domain tag for a nonced block-tree internal node.
110const DOMAIN_BLOCK_NODE: &[u8] = b"autonomi.ant.audit.slice.block-node.v1";
111
112/// Domain-separation context for deriving the per-audit BLAKE3 key of the
113/// nonced block tree.
114///
115/// Versioned alongside the subtree-audit protocol id and distinct from every
116/// other BLAKE3 use in the replication subsystem.
117const BLOCK_KEY_CONTEXT: &str = "autonomi.ant.audit.slice.block-key.v1";
118
119/// Per-audit keying material for the nonced block tree, derived from the fresh
120/// nonce, the challenged peer and the chunk key. Constant across a chunk's blocks.
121///
122/// Uses BLAKE3's `derive_key` mode. `derive_key` separates domains at the mode
123/// level (its own flag bits), so this key cannot collide with a plain or keyed
124/// hash of the same bytes; a plain hash over a domain prefix would separate only
125/// by convention.
126///
127/// The result is then used as a BLAKE3 **key**, not a message prefix. That is
128/// what forces every BLAKE3 chunk of a block leaf to depend on the nonce: keyed
129/// BLAKE3 mixes the key into the initial state of every chunk compression, so
130/// there is no nonce-independent chaining value. Prefixing the nonce instead
131/// leaves the block's tail in a second, nonce-free BLAKE3 chunk whose chaining
132/// value is precomputable (leaf input is `domain ‖ nonce ‖ … ‖ block`, ~1166
133/// bytes, so the last ~142 block bytes fall in chunk 1 with no nonce), letting a
134/// node store ~10.7% less than each block and still reconstruct the leaf for any
135/// fresh nonce.
136///
137#[must_use]
138fn nonced_block_key(nonce: &[u8; 32], peer: &[u8; 32], key: &XorName) -> [u8; 32] {
139    let mut h = blake3::Hasher::new_derive_key(BLOCK_KEY_CONTEXT);
140    h.update(nonce);
141    h.update(peer);
142    h.update(key);
143    *h.finalize().as_bytes()
144}
145
146/// Number of 1 KiB blocks covering `content_len` bytes.
147///
148/// Always at least 1 (an empty chunk is one empty block) so every committed key
149/// opens at least one block, and the block index the auditor draws is always in
150/// range.
151#[must_use]
152pub fn block_count(content_len: u64) -> u32 {
153    if content_len == 0 {
154        return 1;
155    }
156    u32::try_from(content_len.div_ceil(AUDIT_BLOCK_SIZE)).unwrap_or(u32::MAX)
157}
158
159/// Byte range `[start, end)` of block `index` within `content_len` bytes.
160///
161/// The final block may be short; an out-of-range index clamps to an empty range
162/// at `content_len` (callers never pass one — the auditor draws indices in
163/// `0..block_count`).
164#[must_use]
165pub fn block_range(content_len: u64, index: u32) -> (u64, u64) {
166    let start = u64::from(index)
167        .saturating_mul(AUDIT_BLOCK_SIZE)
168        .min(content_len);
169    let end = start.saturating_add(AUDIT_BLOCK_SIZE).min(content_len);
170    (start, end)
171}
172
173/// Slice a block's bytes out of a full chunk. Returns an empty slice for an
174/// out-of-range index (never happens for auditor-drawn indices).
175#[must_use]
176fn block_bytes(content: &[u8], index: u32) -> &[u8] {
177    let (start, end) = block_range(content.len() as u64, index);
178    let start = usize::try_from(start).unwrap_or(usize::MAX);
179    let end = usize::try_from(end).unwrap_or(usize::MAX);
180    content.get(start..end).unwrap_or(&[])
181}
182
183/// Nonced block-leaf hash: keyed by the per-audit key (nonce/peer/key) so every
184/// BLAKE3 chunk of the leaf depends on the nonce, binding the block index, block
185/// length and block bytes with no nonce-independent state to precompute.
186///
187/// See [`nonced_block_key`] for why the nonce is a key, not a prefix.
188#[must_use]
189fn nonced_block_leaf(
190    nonce: &[u8; 32],
191    peer: &[u8; 32],
192    key: &XorName,
193    index: u32,
194    block: &[u8],
195) -> [u8; 32] {
196    let audit_key = nonced_block_key(nonce, peer, key);
197    let mut h = blake3::Hasher::new_keyed(&audit_key);
198    h.update(DOMAIN_BLOCK_LEAF);
199    h.update(&index.to_le_bytes());
200    let block_len = u32::try_from(block.len()).unwrap_or(u32::MAX);
201    h.update(&block_len.to_le_bytes());
202    h.update(block);
203    *h.finalize().as_bytes()
204}
205
206/// Combine two child hashes into a nonced block-tree internal node.
207#[must_use]
208fn nonced_block_node(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
209    let mut h = blake3::Hasher::new();
210    h.update(DOMAIN_BLOCK_NODE);
211    h.update(left);
212    h.update(right);
213    *h.finalize().as_bytes()
214}
215
216/// Fold one level of a left-packed Merkle tree, self-pairing an unpaired last
217/// node (`node(x, x)`) exactly like the commitment tree.
218#[must_use]
219fn fold_level(level: &[[u8; 32]]) -> Vec<[u8; 32]> {
220    let mut next = Vec::with_capacity(level.len().div_ceil(2));
221    let mut i = 0;
222    while i < level.len() {
223        let left = level.get(i).copied().unwrap_or([0u8; 32]);
224        // Self-pair the last node when the level has an odd length.
225        let right = level.get(i + 1).copied().unwrap_or(left);
226        next.push(nonced_block_node(&left, &right));
227        i += 2;
228    }
229    next
230}
231
232/// The nonced block-tree leaves for a chunk's `content`, in block order.
233#[must_use]
234fn nonced_leaves(
235    nonce: &[u8; 32],
236    peer: &[u8; 32],
237    key: &XorName,
238    content: &[u8],
239) -> Vec<[u8; 32]> {
240    let count = block_count(content.len() as u64);
241    (0..count)
242        .map(|i| nonced_block_leaf(nonce, peer, key, i, block_bytes(content, i)))
243        .collect()
244}
245
246/// Compute the nonced block-tree root over a chunk's `content` (responder, round
247/// 1). Requires every byte of the chunk, under the fresh nonce.
248#[must_use]
249pub fn nonced_block_root(
250    nonce: &[u8; 32],
251    peer: &[u8; 32],
252    key: &XorName,
253    content: &[u8],
254) -> [u8; 32] {
255    let mut level = nonced_leaves(nonce, peer, key, content);
256    // A single leaf is its own root (matches the commitment tree's convention).
257    while level.len() > 1 {
258        level = fold_level(&level);
259    }
260    level.first().copied().unwrap_or([0u8; 32])
261}
262
263/// Sibling hashes on the path from block `index` up to the nonced root,
264/// bottom-up (leaf level first). `None` if `index` is out of range for the tree.
265///
266/// The verifier folds the recomputed leaf with these siblings using node-index
267/// parity, so the sibling ordering is positional, not left/right-tagged.
268#[must_use]
269pub fn nonced_block_siblings(
270    nonce: &[u8; 32],
271    peer: &[u8; 32],
272    key: &XorName,
273    content: &[u8],
274    index: u32,
275) -> Option<Vec<[u8; 32]>> {
276    siblings_from_leaves(&nonced_leaves(nonce, peer, key, content), index)
277}
278
279/// Sibling chain for `index` from prebuilt nonced leaves (no per-leaf rehash).
280///
281/// Folding 32-byte CVs is cheap; the cost is computing the leaves, so callers
282/// that open several blocks of one chunk build the leaves once and fold here per
283/// block. `None` if `index` is out of range.
284#[must_use]
285fn siblings_from_leaves(leaves: &[[u8; 32]], index: u32) -> Option<Vec<[u8; 32]>> {
286    if usize::try_from(index).ok()? >= leaves.len() {
287        return None;
288    }
289    let mut level = leaves.to_vec();
290    let mut node_index = index as usize;
291    let mut siblings = Vec::new();
292    while level.len() > 1 {
293        // Sibling is the other child of this node's parent; the last node of an
294        // odd level self-pairs, so its sibling is itself.
295        let sibling_index = node_index ^ 1;
296        let sibling = level
297            .get(sibling_index)
298            .or_else(|| level.get(node_index))
299            .copied()
300            .unwrap_or([0u8; 32]);
301        siblings.push(sibling);
302        node_index /= 2;
303        level = fold_level(&level);
304    }
305    Some(siblings)
306}
307
308/// Verify a nonced block opening (auditor, round 2): recompute the block leaf
309/// from the served bytes and fold it with `siblings` to the committed
310/// `nonced_root`.
311///
312/// `block` must be the Bao-verified block bytes for `index`, so this proves the
313/// responder committed a nonced root over the *real* content at round-1 time.
314#[must_use]
315#[allow(clippy::too_many_arguments)]
316pub fn verify_nonced_block(
317    nonce: &[u8; 32],
318    peer: &[u8; 32],
319    key: &XorName,
320    index: u32,
321    block: &[u8],
322    siblings: &[[u8; 32]],
323    nonced_root: &[u8; 32],
324    block_count: u32,
325) -> bool {
326    // Enforce the canonical tree geometry: the sibling chain MUST be exactly the
327    // depth of a `block_count`-leaf tree. `nonced_root` is responder-chosen in
328    // round 1, so without this a partial holder could set `nonced_root` to a
329    // single block's leaf and pass with zero siblings whenever the fresh draw
330    // happens to land on that block. Pinning the depth binds the claimed
331    // left-packed geometry and rejects such degraded proofs.
332    if siblings.len() != nonced_tree_depth(block_count) {
333        return false;
334    }
335    // An index past the last block names no leaf of the committed tree, so there
336    // is nothing it could legitimately open. Production requests are always in
337    // range; rejecting here makes a malformed or forged one fail deterministically
338    // and cheaply, rather than folding a hash chain to reach the same answer.
339    if index >= block_count {
340        return false;
341    }
342    let mut node_index = index as usize;
343    let mut cur = nonced_block_leaf(nonce, peer, key, index, block);
344    for sibling in siblings {
345        cur = if node_index % 2 == 0 {
346            nonced_block_node(&cur, sibling)
347        } else {
348            nonced_block_node(sibling, &cur)
349        };
350        node_index /= 2;
351    }
352    &cur == nonced_root
353}
354
355/// Canonical sibling-chain length for a `block_count`-leaf nonced tree.
356///
357/// The number of `div_ceil(2)` folds from the leaf level down to a single root
358/// (0 for a single-block chunk). Matches [`nonced_block_siblings`]'s output.
359#[must_use]
360pub fn nonced_tree_depth(block_count: u32) -> usize {
361    let mut n = block_count.max(1) as usize;
362    let mut depth = 0;
363    while n > 1 {
364        n = n.div_ceil(2);
365        depth += 1;
366    }
367    depth
368}
369
370/// Extract a Bao verified slice for block `index` of `content` (responder, round
371/// 2). The slice carries the block bytes plus the O(log n) BLAKE3 parent hashes
372/// that verify it against the chunk address.
373///
374/// # Errors
375///
376/// Returns the underlying IO error only if the in-memory Bao extraction fails,
377/// which cannot happen for a well-formed in-memory chunk; surfaced as a
378/// `Result` rather than a panic so the responder degrades to a rejection.
379pub fn extract_block_slice(content: &[u8], index: u32) -> std::io::Result<Vec<u8>> {
380    // The outboard carries the BLAKE3 tree hashes separately from the content, so
381    // the extractor reads the real chunk bytes plus just the parent hashes on the
382    // block's path — no need to materialise a full Bao encoding of the chunk.
383    let (outboard, _hash) = bao::encode::outboard(content);
384    extract_block_slice_with_outboard(content, &outboard, index)
385}
386
387/// Extract a Bao verified slice for block `index` reusing a prebuilt `outboard`.
388///
389/// Building the outboard hashes the whole chunk, so when several blocks of the
390/// same chunk are opened in one challenge (round + final, plus any dedup), the
391/// caller builds the outboard once (see [`ChunkOpener`]) and calls this per
392/// block instead of re-hashing. Borrows `content` directly (no copy).
393///
394/// # Errors
395///
396/// Surfaces an in-memory Bao extraction error as a `Result` rather than a panic;
397/// it cannot happen for a well-formed in-memory chunk and outboard.
398pub fn extract_block_slice_with_outboard(
399    content: &[u8],
400    outboard: &[u8],
401    index: u32,
402) -> std::io::Result<Vec<u8>> {
403    let (start, end) = block_range(content.len() as u64, index);
404    let len = end - start;
405    let mut extractor = bao::encode::SliceExtractor::new_outboard(
406        Cursor::new(content),
407        Cursor::new(outboard),
408        start,
409        len,
410    );
411    let mut slice = Vec::new();
412    extractor.read_to_end(&mut slice)?;
413    Ok(slice)
414}
415
416/// Reusable per-chunk responder state for building round-2 openings.
417///
418/// Building the Bao outboard and the nonced block-tree leaves each hash the full
419/// chunk. When one challenge opens several blocks of the same chunk (the normal
420/// random + final pair, plus any duplicates), doing that work once and serving
421/// every opening from it keeps a multi-opening challenge to a single hashing pass
422/// over the bytes instead of one per opening (V2-685 round-2 amplification fix).
423pub struct ChunkOpener<'a> {
424    content: &'a [u8],
425    outboard: Vec<u8>,
426    leaves: Vec<[u8; 32]>,
427}
428
429impl<'a> ChunkOpener<'a> {
430    /// Build the chunk's reusable opening state once: its Bao outboard and its
431    /// nonced block-leaves (two hash passes over the resident chunk). Repeated
432    /// openings of the same chunk reuse this state instead of rehashing per opening.
433    #[must_use]
434    pub fn new(nonce: &[u8; 32], peer: &[u8; 32], key: &XorName, content: &'a [u8]) -> Self {
435        let (outboard, _hash) = bao::encode::outboard(content);
436        let leaves = nonced_leaves(nonce, peer, key, content);
437        Self {
438            content,
439            outboard,
440            leaves,
441        }
442    }
443
444    /// Number of 1 KiB blocks in the chunk (always ≥ 1).
445    #[must_use]
446    pub fn block_count(&self) -> u32 {
447        u32::try_from(self.leaves.len()).unwrap_or(u32::MAX)
448    }
449
450    /// Bao verified slice for `index`, reusing the prebuilt outboard.
451    ///
452    /// # Errors
453    /// Surfaces an in-memory Bao extraction error as a `Result` rather than a panic.
454    pub fn bao_slice(&self, index: u32) -> std::io::Result<Vec<u8>> {
455        extract_block_slice_with_outboard(self.content, &self.outboard, index)
456    }
457
458    /// Nonced-tree sibling chain for `index`, reusing the prebuilt leaves.
459    #[must_use]
460    pub fn nonced_siblings(&self, index: u32) -> Option<Vec<[u8; 32]>> {
461        siblings_from_leaves(&self.leaves, index)
462    }
463}
464
465/// Size of the Bao slice's leading length header (a little-endian `u64` giving
466/// the encoded content's total length, in bytes). This is the first field of
467/// every Bao slice; the decoder authenticates it against the tree root, so it
468/// cannot be forged to disagree with the `address` the slice verifies against.
469const BAO_LENGTH_HEADER_SIZE: usize = 8;
470
471/// Verify a Bao slice for block `index` against the chunk `address`
472/// (`BLAKE3(content)`), returning the verified block bytes (auditor, round 2).
473///
474/// `content_len` is the responder's round-1 claim. It is NOT bound by the signed
475/// commitment (the Merkle leaf hashes only `key ‖ bytes_hash`), so a malicious
476/// responder can claim any length. Left unchecked, a **deflation** lie forges
477/// possession: claiming `content_len = 1024` for a 4 MiB chunk collapses
478/// `block_count` to 1, so the auditor can only ever open block 0, and a Bao
479/// slice for the prefix range `[0, 1024)` verifies fine against the true
480/// full-content address — a node storing ~1 KiB passes an audit for the whole
481/// chunk. To close this, the slice's own authenticated length header (which the
482/// decoder validates against `address`, so it equals the *true* content length)
483/// must match the claimed `content_len`. A responder that lies about the length
484/// then either fails the header check (claim ≠ true length) or is forced to
485/// report the true length — in which case the block index is drawn from the full
486/// range and possession of all blocks is required.
487#[must_use]
488pub fn verify_block_slice(
489    slice: &[u8],
490    address: &[u8; 32],
491    content_len: u64,
492    index: u32,
493) -> Option<Vec<u8>> {
494    // Authenticate the claimed length against the slice's own header before
495    // trusting `content_len` for the block range. The header is the first 8
496    // bytes of every Bao slice and is validated against `address` by the decode
497    // below (a forged header changes the tree shape and fails the root check),
498    // so requiring it to equal `content_len` forces the claim to be the true
499    // content length — defeating the deflation forgery described above.
500    let header = slice.get(..BAO_LENGTH_HEADER_SIZE)?;
501    let declared_len = u64::from_le_bytes(header.try_into().ok()?);
502    if declared_len != content_len {
503        return None;
504    }
505
506    // Reject an out-of-range index outright. `block_range` clamps one to the
507    // empty range `[content_len, content_len)`, which would decode to an empty
508    // block and return `Some(vec![])` — a malformed request reading as a
509    // partially valid answer. Nothing legitimate opens a block that does not
510    // exist.
511    if index >= block_count(content_len) {
512        return None;
513    }
514
515    let (start, end) = block_range(content_len, index);
516    let len = end - start;
517    let hash = blake3::Hash::from_bytes(*address);
518    let mut decoder = bao::decode::SliceDecoder::new(Cursor::new(slice), &hash, start, len);
519    let mut verified = Vec::new();
520    decoder.read_to_end(&mut verified).ok()?;
521    if verified.len() as u64 != len {
522        return None;
523    }
524    Some(verified)
525}
526
527#[cfg(test)]
528#[allow(
529    clippy::unwrap_used,
530    clippy::expect_used,
531    clippy::panic,
532    clippy::cast_possible_truncation
533)]
534mod tests {
535    use super::*;
536
537    const NONCE: [u8; 32] = [0x11; 32];
538    const PEER: [u8; 32] = [0x22; 32];
539    const KEY: XorName = [0x33; 32];
540
541    /// Deterministic pseudo-content of a given length (avoids RNG in tests).
542    fn content_of(len: usize) -> Vec<u8> {
543        (0..len).map(|i| (i * 31 + 7) as u8).collect()
544    }
545
546    // -- block geometry -----------------------------------------------------
547
548    #[test]
549    fn block_count_is_ceil_with_empty_floor() {
550        assert_eq!(block_count(0), 1);
551        assert_eq!(block_count(1), 1);
552        assert_eq!(block_count(1024), 1);
553        assert_eq!(block_count(1025), 2);
554        assert_eq!(block_count(4096), 4);
555        assert_eq!(block_count(4 * 1024 * 1024), 4096);
556        assert_eq!(block_count(4 * 1024 * 1024 - 1), 4096);
557    }
558
559    #[test]
560    fn block_range_covers_content_without_gaps_or_overlap() {
561        let len = 1024 * 3 + 500;
562        let count = block_count(len);
563        let mut expected_start = 0u64;
564        for i in 0..count {
565            let (s, e) = block_range(len, i);
566            assert_eq!(s, expected_start);
567            assert!(e <= len);
568            assert!(e > s || len == 0);
569            expected_start = e;
570        }
571        assert_eq!(expected_start, len);
572    }
573
574    // -- bao slice == blake3 address ---------------------------------------
575
576    #[test]
577    fn bao_root_equals_blake3_address_across_lengths() {
578        // The whole design rests on Bao's root being the chunk's BLAKE3 address.
579        for len in [0usize, 1, 1023, 1024, 1025, 2048, 4096, 10_000, 1 << 20] {
580            let content = content_of(len);
581            let (_outboard, bao_hash) = bao::encode::outboard(&content);
582            let blake = blake3::hash(&content);
583            assert_eq!(
584                bao_hash.as_bytes(),
585                blake.as_bytes(),
586                "bao root must equal blake3(content) at len {len}"
587            );
588        }
589    }
590
591    // Both verifiers reject a block index past the end of the chunk. Nothing the
592    // auditor generates is ever out of range, so this is about failing cleanly:
593    // `block_range` clamps an over-large index to an empty range, which without
594    // the check reads back as a successfully verified empty block rather than as
595    // the malformed request it is.
596    #[test]
597    fn verifiers_reject_a_block_index_past_the_end() {
598        let len = 4096usize;
599        let content = content_of(len);
600        let address = *blake3::hash(&content).as_bytes();
601        let count = block_count(len as u64);
602
603        // A real slice for the last block does not become a valid opening for a
604        // block that does not exist.
605        let slice = extract_block_slice(&content, count - 1).expect("extract");
606        assert!(
607            verify_block_slice(&slice, &address, len as u64, count).is_none(),
608            "the first index past the end must be rejected, not read as empty"
609        );
610        assert!(verify_block_slice(&slice, &address, len as u64, u32::MAX).is_none());
611
612        // Same on the possession chain, with a genuine sibling path.
613        let siblings =
614            nonced_block_siblings(&NONCE, &PEER, &KEY, &content, count - 1).expect("siblings");
615        let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
616        let (s, e) = block_range(len as u64, count - 1);
617        let block = &content[s as usize..e as usize];
618        assert!(
619            !verify_nonced_block(&NONCE, &PEER, &KEY, count, block, &siblings, &root, count),
620            "an index past the last leaf names nothing in the committed tree"
621        );
622    }
623
624    #[test]
625    fn slice_roundtrip_verifies_every_block() {
626        for len in [1usize, 1024, 1025, 4096, 5000, 1 << 16] {
627            let content = content_of(len);
628            let address = *blake3::hash(&content).as_bytes();
629            let count = block_count(len as u64);
630            for i in 0..count {
631                let slice = extract_block_slice(&content, i).expect("extract");
632                let verified =
633                    verify_block_slice(&slice, &address, len as u64, i).expect("verify slice");
634                let (s, e) = block_range(len as u64, i);
635                assert_eq!(verified.as_slice(), &content[s as usize..e as usize]);
636            }
637        }
638    }
639
640    // Regression: content_len deflation must NOT forge possession.
641    //
642    // `content_len` is not bound by the signed round-1 commitment (the Merkle
643    // leaf hashes only key+bytes_hash), so a malicious responder can claim
644    // content_len=1024 for a 1 MiB chunk. That would collapse block_count to 1,
645    // let the auditor only ever open block 0, and — before the fix — pass a Bao
646    // slice for the prefix [0,1024) against the true full-content address while
647    // storing ~1 KiB. verify_block_slice now authenticates the slice's own length
648    // header against the claim, so the deflation is rejected at chain 1.
649    #[test]
650    fn content_len_deflation_is_rejected() {
651        let full = content_of(1 << 20); // 1 MiB chunk, truly 1024 blocks.
652        let address = *blake3::hash(&full).as_bytes();
653
654        // Attacker keeps only the first block's Bao slice (extracted honestly for
655        // range [0,1024) of the real content), discarding the rest of the 1 MiB.
656        let stored_slice = extract_block_slice(&full, 0).expect("extract block 0");
657
658        // Round 1: attacker claims content_len = 1024 (one block).
659        let claimed_len = 1024u64;
660        assert_eq!(block_count(claimed_len), 1, "deflated claim = one block");
661
662        // Round 2: only block 0 could be drawn. Chain 1 must reject because the
663        // slice's authenticated length header (1 MiB) disagrees with the claim.
664        assert!(
665            verify_block_slice(&stored_slice, &address, claimed_len, 0).is_none(),
666            "deflated content_len must fail the slice length-header check"
667        );
668
669        // An honest responder reporting the true length still verifies block 0.
670        let honest = verify_block_slice(&stored_slice, &address, (1 << 20) as u64, 0);
671        assert_eq!(
672            honest.expect("honest full-length slice must verify").len(),
673            1024
674        );
675    }
676
677    /// Rewrite a Bao slice's 8-byte little-endian length header in place.
678    fn rewrite_slice_len(slice: &mut [u8], forged_len: u64) {
679        slice[..BAO_LENGTH_HEADER_SIZE].copy_from_slice(&forged_len.to_le_bytes());
680    }
681
682    // Regression for the header-rewrite length forgery (the residual attack the
683    // plain header==content_len check does NOT catch on its own).
684    //
685    // Bao does not cryptographically bind the length header for a PREFIX slice
686    // that never touches EOF: the unopened right subtree is an opaque hash. So an
687    // attacker can claim `content_len` just past a subtree boundary (e.g. 2 KiB+1
688    // for a 4 KiB / 4-block chunk), REWRITE each slice header to that forged
689    // length, supply the true right-subtree CV as the opaque root sibling, and
690    // pass any opening in the retained left half — storing only that half. The
691    // header check passes because header == forged content_len.
692    //
693    // The defence is to ALSO open the CLAIMED FINAL block: that decode reaches
694    // EOF, where Bao authenticates the encoded length against the address, so a
695    // forged-short length fails. This test shows both halves: a left-half opening
696    // slips past the header check, but the final-block opening rejects the forgery.
697    #[test]
698    fn header_rewrite_length_forgery_is_caught_at_the_final_block() {
699        // True chunk: 4 blocks. Root = parent(parent(b0,b1), parent(b2,b3)).
700        let full = content_of(4096);
701        let address = *blake3::hash(&full).as_bytes();
702
703        // Forged length: 2049 bytes → block_count 3 (b0, b1 full, b2' one byte).
704        // The claimed final block is index 2; blocks 0..2 are the retained half.
705        let forged_len = 2049u64;
706        assert_eq!(block_count(forged_len), 3);
707        let forged_final = block_count(forged_len) - 1;
708
709        // Left-half opening (block 0): the attacker rewrites an honest block-0
710        // slice's header to the forged length. The retained slice already carries
711        // the true right-subtree CV as the opaque root sibling, so it verifies
712        // against the real address AND passes the header==content_len check.
713        let mut left = extract_block_slice(&full, 0).expect("extract block 0");
714        rewrite_slice_len(&mut left, forged_len);
715        assert!(
716            verify_block_slice(&left, &address, forged_len, 0).is_some(),
717            "header rewrite lets a left-half opening slip past the header check — \
718             this is exactly why the final block must also be opened"
719        );
720
721        // Final-block opening (block 2 under the forged length): no slice the
722        // attacker can offer verifies, because reaching the forged EOF forces Bao
723        // to authenticate the length against the true address. The best attempt —
724        // an honest block-2 slice of the true content with a rewritten header —
725        // is rejected.
726        let mut fake_final = extract_block_slice(&full, 2).expect("extract block 2");
727        rewrite_slice_len(&mut fake_final, forged_len);
728        assert!(
729            verify_block_slice(&fake_final, &address, forged_len, forged_final).is_none(),
730            "final-block opening under a forged short length must fail (EOF length auth)"
731        );
732    }
733
734    #[test]
735    fn slice_against_wrong_address_fails() {
736        let content = content_of(4096);
737        let mut wrong = *blake3::hash(&content).as_bytes();
738        wrong[0] ^= 0x01;
739        let slice = extract_block_slice(&content, 2).expect("extract");
740        assert!(verify_block_slice(&slice, &wrong, 4096, 2).is_none());
741    }
742
743    #[test]
744    fn tampered_slice_bytes_fail_verification() {
745        let content = content_of(4096);
746        let address = *blake3::hash(&content).as_bytes();
747        let mut slice = extract_block_slice(&content, 1).expect("extract");
748        // Corrupt the payload bytes near the end of the slice (a data byte).
749        if let Some(b) = slice.last_mut() {
750            *b ^= 0xFF;
751        }
752        assert!(verify_block_slice(&slice, &address, 4096, 1).is_none());
753    }
754
755    #[test]
756    fn slice_for_one_block_cannot_serve_a_different_block() {
757        let content = content_of(4096);
758        let address = *blake3::hash(&content).as_bytes();
759        let slice = extract_block_slice(&content, 0).expect("extract");
760        // A slice built for block 0 must not verify as block 2.
761        assert!(verify_block_slice(&slice, &address, 4096, 2).is_none());
762    }
763
764    // -- nonced block tree --------------------------------------------------
765
766    #[test]
767    fn nonced_openings_roundtrip_every_block() {
768        for len in [1usize, 1024, 1025, 3000, 4096, 9001] {
769            let content = content_of(len);
770            let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
771            let count = block_count(len as u64);
772            for i in 0..count {
773                let siblings =
774                    nonced_block_siblings(&NONCE, &PEER, &KEY, &content, i).expect("siblings");
775                let block = block_bytes(&content, i);
776                assert!(
777                    verify_nonced_block(&NONCE, &PEER, &KEY, i, block, &siblings, &root, count),
778                    "len {len} block {i} must verify"
779                );
780            }
781        }
782    }
783
784    #[test]
785    fn nonced_opening_rejects_wrong_block_bytes() {
786        let content = content_of(4096);
787        let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
788        let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 1).expect("siblings");
789        let mut wrong = block_bytes(&content, 1).to_vec();
790        wrong[0] ^= 0x01;
791        let bc = block_count(content.len() as u64);
792        assert!(!verify_nonced_block(
793            &NONCE, &PEER, &KEY, 1, &wrong, &siblings, &root, bc
794        ));
795    }
796
797    #[test]
798    fn nonced_opening_binds_nonce_peer_and_key() {
799        let content = content_of(4096);
800        let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
801        let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 2).expect("siblings");
802        let block = block_bytes(&content, 2);
803        let bc = block_count(content.len() as u64);
804        // Correct binding verifies.
805        assert!(verify_nonced_block(
806            &NONCE, &PEER, &KEY, 2, block, &siblings, &root, bc
807        ));
808        // A different nonce, peer, or key must not verify against the same root.
809        let other = [0xAB; 32];
810        assert!(!verify_nonced_block(
811            &other, &PEER, &KEY, 2, block, &siblings, &root, bc
812        ));
813        assert!(!verify_nonced_block(
814            &NONCE, &other, &KEY, 2, block, &siblings, &root, bc
815        ));
816        assert!(!verify_nonced_block(
817            &NONCE, &PEER, &other, 2, block, &siblings, &root, bc
818        ));
819    }
820
821    // Regression: the nonce must KEY every BLAKE3 chunk of a block
822    // leaf, not merely prefix the message. A prefixed leaf (`BLAKE3(nonce ‖ … ‖
823    // block)`, ~1166 bytes) leaves the block's tail in a second, nonce-free
824    // BLAKE3 chunk whose chaining value is precomputable, letting a node store
825    // ~10.7% less than each block and rebuild the leaf for any fresh nonce. Lock
826    // in the keyed construction and prove it differs from the vulnerable one.
827    #[test]
828    fn leaf_is_keyed_by_the_nonce_not_prefixed() {
829        let block = content_of(1024);
830        let index = 3u32;
831        let block_len = block.len() as u32;
832        let got = nonced_block_leaf(&NONCE, &PEER, &KEY, index, &block);
833
834        // Required construction: keyed BLAKE3, nonce in the key.
835        let audit_key = nonced_block_key(&NONCE, &PEER, &KEY);
836        let mut keyed = blake3::Hasher::new_keyed(&audit_key);
837        keyed.update(DOMAIN_BLOCK_LEAF);
838        keyed.update(&index.to_le_bytes());
839        keyed.update(&block_len.to_le_bytes());
840        keyed.update(&block);
841        assert_eq!(
842            got,
843            *keyed.finalize().as_bytes(),
844            "leaf must be keyed BLAKE3 with the nonce-derived key"
845        );
846
847        // The old, vulnerable prefixed construction must NOT match.
848        let mut prefixed = blake3::Hasher::new();
849        prefixed.update(DOMAIN_BLOCK_LEAF);
850        prefixed.update(&NONCE);
851        prefixed.update(&PEER);
852        prefixed.update(&KEY);
853        prefixed.update(&index.to_le_bytes());
854        prefixed.update(&block_len.to_le_bytes());
855        prefixed.update(&block);
856        assert_ne!(
857            got,
858            *prefixed.finalize().as_bytes(),
859            "leaf must not use the precomputable prefixed-nonce construction"
860        );
861    }
862
863    // The documented strength claim, made executable: a partial holder CAN pass,
864    // and what stops it is sampling, not the hash construction.
865    //
866    // A peer keeping blocks 0..k of a chunk commits a root whose kept-block
867    // leaves are genuine and whose dropped-block leaves are garbage. Every
868    // opening on a kept block verifies against that root; every opening on a
869    // dropped block fails. This is the whole basis for describing round 2 as a
870    // sampling check rather than a proof of complete possession.
871    #[test]
872    fn partial_holder_passes_on_kept_blocks_and_fails_on_dropped_ones() {
873        let content = content_of(8 * 1024); // 8 blocks
874        let count = block_count(content.len() as u64);
875        assert_eq!(count, 8);
876        let kept = 5u32; // blocks 0..5 retained, 5..8 dropped
877
878        // Build the tree a partial holder would commit: real leaves for kept
879        // blocks, arbitrary (wrong) leaves for the dropped ones.
880        let leaves: Vec<[u8; 32]> = (0..count)
881            .map(|i| {
882                if i < kept {
883                    nonced_block_leaf(&NONCE, &PEER, &KEY, i, block_bytes(&content, i))
884                } else {
885                    // No bytes for this block — anything at all goes here.
886                    nonced_block_leaf(&NONCE, &PEER, &KEY, i, b"dropped")
887                }
888            })
889            .collect();
890        let mut level = leaves.clone();
891        while level.len() > 1 {
892            level = fold_level(&level);
893        }
894        let forged_root = level.first().copied().expect("non-empty tree");
895
896        // An opening on a KEPT block verifies against the forged root: the peer
897        // passes this draw despite not holding the whole chunk.
898        for i in 0..kept {
899            let siblings = siblings_from_leaves(&leaves, i).expect("in range");
900            assert!(
901                verify_nonced_block(
902                    &NONCE,
903                    &PEER,
904                    &KEY,
905                    i,
906                    block_bytes(&content, i),
907                    &siblings,
908                    &forged_root,
909                    count,
910                ),
911                "a kept block must verify — this is the false-pass path the docs describe"
912            );
913        }
914
915        // An opening on a DROPPED block cannot be answered: the peer has no
916        // bytes whose leaf folds to the committed root at that index.
917        for i in kept..count {
918            let siblings = siblings_from_leaves(&leaves, i).expect("in range");
919            assert!(
920                !verify_nonced_block(
921                    &NONCE,
922                    &PEER,
923                    &KEY,
924                    i,
925                    block_bytes(&content, i),
926                    &siblings,
927                    &forged_root,
928                    count,
929                ),
930                "a dropped block must fail — sampling is what catches the partial holder"
931            );
932        }
933    }
934
935    // The slice proof uses BLAKE3 `derive_key` mode over
936    // `nonce ‖ peer ‖ key` under a subtree-specific context string.
937    #[test]
938    fn block_key_uses_the_subtree_domain_separated_derivation() {
939        let mut expected = blake3::Hasher::new_derive_key(BLOCK_KEY_CONTEXT);
940        expected.update(&NONCE);
941        expected.update(&PEER);
942        expected.update(&KEY);
943        assert_eq!(
944            nonced_block_key(&NONCE, &PEER, &KEY),
945            *expected.finalize().as_bytes(),
946            "block key must use derive_key mode"
947        );
948
949        // Mode separation is the point: the same material under a plain hash,
950        // or under keyed mode, must land somewhere else entirely.
951        let mut plain = blake3::Hasher::new();
952        plain.update(BLOCK_KEY_CONTEXT.as_bytes());
953        plain.update(&NONCE);
954        plain.update(&PEER);
955        plain.update(&KEY);
956        assert_ne!(
957            nonced_block_key(&NONCE, &PEER, &KEY),
958            *plain.finalize().as_bytes(),
959            "derive_key mode must not coincide with a plain domain-prefixed hash"
960        );
961    }
962
963    #[test]
964    fn nonced_root_changes_with_any_block_edit() {
965        let content = content_of(5000);
966        let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
967        let mut edited = content;
968        // Flip a byte in the LAST block; the root must change (all blocks covered).
969        if let Some(b) = edited.last_mut() {
970            *b ^= 0x01;
971        }
972        let root2 = nonced_block_root(&NONCE, &PEER, &KEY, &edited);
973        assert_ne!(root, root2);
974    }
975
976    #[test]
977    fn nonced_siblings_out_of_range_is_none() {
978        let content = content_of(2048);
979        let count = block_count(content.len() as u64);
980        assert!(nonced_block_siblings(&NONCE, &PEER, &KEY, &content, count).is_none());
981    }
982
983    // -- the combined possession property ----------------------------------
984
985    #[test]
986    fn relay_cannot_open_against_a_foreign_committed_root() {
987        // A responder that did NOT hold the bytes at round 1 commits a root over
988        // garbage (or a guess). Even if it later fetches the real block, folding
989        // the real leaf to that committed root would be a preimage break: model
990        // this by taking a root from DIFFERENT content and checking that the real
991        // block + honest siblings never fold to it.
992        let real = content_of(4096);
993        let garbage = content_of(4097); // different content => different tree
994        let foreign_root = nonced_block_root(&NONCE, &PEER, &KEY, &garbage);
995        let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &real, 0).expect("siblings");
996        let block = block_bytes(&real, 0);
997        assert!(!verify_nonced_block(
998            &NONCE,
999            &PEER,
1000            &KEY,
1001            0,
1002            block,
1003            &siblings,
1004            &foreign_root,
1005            block_count(real.len() as u64)
1006        ));
1007    }
1008
1009    // Canonical-depth regression: `nonced_root` is responder-chosen in round 1,
1010    // so a partial holder could set it to a single block's leaf and pass with
1011    // zero siblings whenever the fresh draw lands on that block. Pinning the
1012    // sibling-chain length to the tree depth rejects that (and any wrong-depth
1013    // chain) even when it would fold to the supplied root.
1014    #[test]
1015    fn canonical_depth_rejects_wrong_sibling_count() {
1016        let content = content_of(4096); // 4 blocks → canonical depth 2
1017        let bc = block_count(content.len() as u64);
1018        assert_eq!(nonced_tree_depth(bc), 2);
1019        let block0 = block_bytes(&content, 0);
1020
1021        // Degraded escape: claim root = block 0's own leaf, supply zero siblings.
1022        // Folds to that root, but depth 0 != 2, so rejected.
1023        let leaf0 = nonced_block_leaf(&NONCE, &PEER, &KEY, 0, block0);
1024        assert!(!verify_nonced_block(
1025            &NONCE,
1026            &PEER,
1027            &KEY,
1028            0,
1029            block0,
1030            &[],
1031            &leaf0,
1032            bc
1033        ));
1034
1035        // The honest, correct-depth opening still verifies.
1036        let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
1037        let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 0).expect("siblings");
1038        assert_eq!(siblings.len(), 2);
1039        assert!(verify_nonced_block(
1040            &NONCE, &PEER, &KEY, 0, block0, &siblings, &root, bc
1041        ));
1042
1043        // A too-long chain (extra sibling) is rejected on depth alone.
1044        let mut too_long = siblings;
1045        too_long.push([0u8; 32]);
1046        assert!(!verify_nonced_block(
1047            &NONCE, &PEER, &KEY, 0, block0, &too_long, &root, bc
1048        ));
1049    }
1050}