use std::io::{Cursor, Read};
use crate::ant_protocol::XorName;
pub const AUDIT_BLOCK_SIZE: u64 = 1024;
const DOMAIN_BLOCK_LEAF: &[u8] = b"autonomi.ant.audit.slice.block-leaf.v1";
const DOMAIN_BLOCK_NODE: &[u8] = b"autonomi.ant.audit.slice.block-node.v1";
const BLOCK_KEY_CONTEXT: &str = "autonomi.ant.audit.slice.block-key.v1";
#[must_use]
fn nonced_block_key(nonce: &[u8; 32], peer: &[u8; 32], key: &XorName) -> [u8; 32] {
let mut h = blake3::Hasher::new_derive_key(BLOCK_KEY_CONTEXT);
h.update(nonce);
h.update(peer);
h.update(key);
*h.finalize().as_bytes()
}
#[must_use]
pub fn block_count(content_len: u64) -> u32 {
if content_len == 0 {
return 1;
}
u32::try_from(content_len.div_ceil(AUDIT_BLOCK_SIZE)).unwrap_or(u32::MAX)
}
#[must_use]
pub fn block_range(content_len: u64, index: u32) -> (u64, u64) {
let start = u64::from(index)
.saturating_mul(AUDIT_BLOCK_SIZE)
.min(content_len);
let end = start.saturating_add(AUDIT_BLOCK_SIZE).min(content_len);
(start, end)
}
#[must_use]
fn block_bytes(content: &[u8], index: u32) -> &[u8] {
let (start, end) = block_range(content.len() as u64, index);
let start = usize::try_from(start).unwrap_or(usize::MAX);
let end = usize::try_from(end).unwrap_or(usize::MAX);
content.get(start..end).unwrap_or(&[])
}
#[must_use]
fn nonced_block_leaf(
nonce: &[u8; 32],
peer: &[u8; 32],
key: &XorName,
index: u32,
block: &[u8],
) -> [u8; 32] {
let audit_key = nonced_block_key(nonce, peer, key);
let mut h = blake3::Hasher::new_keyed(&audit_key);
h.update(DOMAIN_BLOCK_LEAF);
h.update(&index.to_le_bytes());
let block_len = u32::try_from(block.len()).unwrap_or(u32::MAX);
h.update(&block_len.to_le_bytes());
h.update(block);
*h.finalize().as_bytes()
}
#[must_use]
fn nonced_block_node(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_BLOCK_NODE);
h.update(left);
h.update(right);
*h.finalize().as_bytes()
}
#[must_use]
fn fold_level(level: &[[u8; 32]]) -> Vec<[u8; 32]> {
let mut next = Vec::with_capacity(level.len().div_ceil(2));
let mut i = 0;
while i < level.len() {
let left = level.get(i).copied().unwrap_or([0u8; 32]);
let right = level.get(i + 1).copied().unwrap_or(left);
next.push(nonced_block_node(&left, &right));
i += 2;
}
next
}
#[must_use]
fn nonced_leaves(
nonce: &[u8; 32],
peer: &[u8; 32],
key: &XorName,
content: &[u8],
) -> Vec<[u8; 32]> {
let count = block_count(content.len() as u64);
(0..count)
.map(|i| nonced_block_leaf(nonce, peer, key, i, block_bytes(content, i)))
.collect()
}
#[must_use]
pub fn nonced_block_root(
nonce: &[u8; 32],
peer: &[u8; 32],
key: &XorName,
content: &[u8],
) -> [u8; 32] {
let mut level = nonced_leaves(nonce, peer, key, content);
while level.len() > 1 {
level = fold_level(&level);
}
level.first().copied().unwrap_or([0u8; 32])
}
#[must_use]
pub fn nonced_block_siblings(
nonce: &[u8; 32],
peer: &[u8; 32],
key: &XorName,
content: &[u8],
index: u32,
) -> Option<Vec<[u8; 32]>> {
siblings_from_leaves(&nonced_leaves(nonce, peer, key, content), index)
}
#[must_use]
fn siblings_from_leaves(leaves: &[[u8; 32]], index: u32) -> Option<Vec<[u8; 32]>> {
if usize::try_from(index).ok()? >= leaves.len() {
return None;
}
let mut level = leaves.to_vec();
let mut node_index = index as usize;
let mut siblings = Vec::new();
while level.len() > 1 {
let sibling_index = node_index ^ 1;
let sibling = level
.get(sibling_index)
.or_else(|| level.get(node_index))
.copied()
.unwrap_or([0u8; 32]);
siblings.push(sibling);
node_index /= 2;
level = fold_level(&level);
}
Some(siblings)
}
#[must_use]
#[allow(clippy::too_many_arguments)]
pub fn verify_nonced_block(
nonce: &[u8; 32],
peer: &[u8; 32],
key: &XorName,
index: u32,
block: &[u8],
siblings: &[[u8; 32]],
nonced_root: &[u8; 32],
block_count: u32,
) -> bool {
if siblings.len() != nonced_tree_depth(block_count) {
return false;
}
if index >= block_count {
return false;
}
let mut node_index = index as usize;
let mut cur = nonced_block_leaf(nonce, peer, key, index, block);
for sibling in siblings {
cur = if node_index.is_multiple_of(2) {
nonced_block_node(&cur, sibling)
} else {
nonced_block_node(sibling, &cur)
};
node_index /= 2;
}
&cur == nonced_root
}
#[must_use]
pub fn nonced_tree_depth(block_count: u32) -> usize {
let mut n = block_count.max(1) as usize;
let mut depth = 0;
while n > 1 {
n = n.div_ceil(2);
depth += 1;
}
depth
}
pub fn extract_block_slice(content: &[u8], index: u32) -> std::io::Result<Vec<u8>> {
let (outboard, _hash) = bao::encode::outboard(content);
extract_block_slice_with_outboard(content, &outboard, index)
}
pub fn extract_block_slice_with_outboard(
content: &[u8],
outboard: &[u8],
index: u32,
) -> std::io::Result<Vec<u8>> {
let (start, end) = block_range(content.len() as u64, index);
let len = end - start;
let mut extractor = bao::encode::SliceExtractor::new_outboard(
Cursor::new(content),
Cursor::new(outboard),
start,
len,
);
let mut slice = Vec::new();
extractor.read_to_end(&mut slice)?;
Ok(slice)
}
pub struct ChunkOpener<'a> {
content: &'a [u8],
outboard: Vec<u8>,
leaves: Vec<[u8; 32]>,
}
impl<'a> ChunkOpener<'a> {
#[must_use]
pub fn new(nonce: &[u8; 32], peer: &[u8; 32], key: &XorName, content: &'a [u8]) -> Self {
let (outboard, _hash) = bao::encode::outboard(content);
let leaves = nonced_leaves(nonce, peer, key, content);
Self {
content,
outboard,
leaves,
}
}
#[must_use]
pub fn block_count(&self) -> u32 {
u32::try_from(self.leaves.len()).unwrap_or(u32::MAX)
}
pub fn bao_slice(&self, index: u32) -> std::io::Result<Vec<u8>> {
extract_block_slice_with_outboard(self.content, &self.outboard, index)
}
#[must_use]
pub fn nonced_siblings(&self, index: u32) -> Option<Vec<[u8; 32]>> {
siblings_from_leaves(&self.leaves, index)
}
}
const BAO_LENGTH_HEADER_SIZE: usize = 8;
#[must_use]
pub fn verify_block_slice(
slice: &[u8],
address: &[u8; 32],
content_len: u64,
index: u32,
) -> Option<Vec<u8>> {
let header = slice.get(..BAO_LENGTH_HEADER_SIZE)?;
let declared_len = u64::from_le_bytes(header.try_into().ok()?);
if declared_len != content_len {
return None;
}
if index >= block_count(content_len) {
return None;
}
let (start, end) = block_range(content_len, index);
let len = end - start;
let hash = blake3::Hash::from_bytes(*address);
let mut decoder = bao::decode::SliceDecoder::new(Cursor::new(slice), &hash, start, len);
let mut verified = Vec::new();
decoder.read_to_end(&mut verified).ok()?;
if verified.len() as u64 != len {
return None;
}
Some(verified)
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::cast_possible_truncation
)]
mod tests {
use super::*;
const NONCE: [u8; 32] = [0x11; 32];
const PEER: [u8; 32] = [0x22; 32];
const KEY: XorName = [0x33; 32];
fn content_of(len: usize) -> Vec<u8> {
(0..len).map(|i| (i * 31 + 7) as u8).collect()
}
#[test]
fn block_count_is_ceil_with_empty_floor() {
assert_eq!(block_count(0), 1);
assert_eq!(block_count(1), 1);
assert_eq!(block_count(1024), 1);
assert_eq!(block_count(1025), 2);
assert_eq!(block_count(4096), 4);
assert_eq!(block_count(4 * 1024 * 1024), 4096);
assert_eq!(block_count(4 * 1024 * 1024 - 1), 4096);
}
#[test]
fn block_range_covers_content_without_gaps_or_overlap() {
let len = 1024 * 3 + 500;
let count = block_count(len);
let mut expected_start = 0u64;
for i in 0..count {
let (s, e) = block_range(len, i);
assert_eq!(s, expected_start);
assert!(e <= len);
assert!(e > s || len == 0);
expected_start = e;
}
assert_eq!(expected_start, len);
}
#[test]
fn bao_root_equals_blake3_address_across_lengths() {
for len in [0usize, 1, 1023, 1024, 1025, 2048, 4096, 10_000, 1 << 20] {
let content = content_of(len);
let (_outboard, bao_hash) = bao::encode::outboard(&content);
let blake = blake3::hash(&content);
assert_eq!(
bao_hash.as_bytes(),
blake.as_bytes(),
"bao root must equal blake3(content) at len {len}"
);
}
}
#[test]
fn verifiers_reject_a_block_index_past_the_end() {
let len = 4096usize;
let content = content_of(len);
let address = *blake3::hash(&content).as_bytes();
let count = block_count(len as u64);
let slice = extract_block_slice(&content, count - 1).expect("extract");
assert!(
verify_block_slice(&slice, &address, len as u64, count).is_none(),
"the first index past the end must be rejected, not read as empty"
);
assert!(verify_block_slice(&slice, &address, len as u64, u32::MAX).is_none());
let siblings =
nonced_block_siblings(&NONCE, &PEER, &KEY, &content, count - 1).expect("siblings");
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let (s, e) = block_range(len as u64, count - 1);
let block = &content[s as usize..e as usize];
assert!(
!verify_nonced_block(&NONCE, &PEER, &KEY, count, block, &siblings, &root, count),
"an index past the last leaf names nothing in the committed tree"
);
}
#[test]
fn slice_roundtrip_verifies_every_block() {
for len in [1usize, 1024, 1025, 4096, 5000, 1 << 16] {
let content = content_of(len);
let address = *blake3::hash(&content).as_bytes();
let count = block_count(len as u64);
for i in 0..count {
let slice = extract_block_slice(&content, i).expect("extract");
let verified =
verify_block_slice(&slice, &address, len as u64, i).expect("verify slice");
let (s, e) = block_range(len as u64, i);
assert_eq!(verified.as_slice(), &content[s as usize..e as usize]);
}
}
}
#[test]
fn content_len_deflation_is_rejected() {
let full = content_of(1 << 20); let address = *blake3::hash(&full).as_bytes();
let stored_slice = extract_block_slice(&full, 0).expect("extract block 0");
let claimed_len = 1024u64;
assert_eq!(block_count(claimed_len), 1, "deflated claim = one block");
assert!(
verify_block_slice(&stored_slice, &address, claimed_len, 0).is_none(),
"deflated content_len must fail the slice length-header check"
);
let honest = verify_block_slice(&stored_slice, &address, (1 << 20) as u64, 0);
assert_eq!(
honest.expect("honest full-length slice must verify").len(),
1024
);
}
fn rewrite_slice_len(slice: &mut [u8], forged_len: u64) {
slice[..BAO_LENGTH_HEADER_SIZE].copy_from_slice(&forged_len.to_le_bytes());
}
#[test]
fn header_rewrite_length_forgery_is_caught_at_the_final_block() {
let full = content_of(4096);
let address = *blake3::hash(&full).as_bytes();
let forged_len = 2049u64;
assert_eq!(block_count(forged_len), 3);
let forged_final = block_count(forged_len) - 1;
let mut left = extract_block_slice(&full, 0).expect("extract block 0");
rewrite_slice_len(&mut left, forged_len);
assert!(
verify_block_slice(&left, &address, forged_len, 0).is_some(),
"header rewrite lets a left-half opening slip past the header check — \
this is exactly why the final block must also be opened"
);
let mut fake_final = extract_block_slice(&full, 2).expect("extract block 2");
rewrite_slice_len(&mut fake_final, forged_len);
assert!(
verify_block_slice(&fake_final, &address, forged_len, forged_final).is_none(),
"final-block opening under a forged short length must fail (EOF length auth)"
);
}
#[test]
fn slice_against_wrong_address_fails() {
let content = content_of(4096);
let mut wrong = *blake3::hash(&content).as_bytes();
wrong[0] ^= 0x01;
let slice = extract_block_slice(&content, 2).expect("extract");
assert!(verify_block_slice(&slice, &wrong, 4096, 2).is_none());
}
#[test]
fn tampered_slice_bytes_fail_verification() {
let content = content_of(4096);
let address = *blake3::hash(&content).as_bytes();
let mut slice = extract_block_slice(&content, 1).expect("extract");
if let Some(b) = slice.last_mut() {
*b ^= 0xFF;
}
assert!(verify_block_slice(&slice, &address, 4096, 1).is_none());
}
#[test]
fn slice_for_one_block_cannot_serve_a_different_block() {
let content = content_of(4096);
let address = *blake3::hash(&content).as_bytes();
let slice = extract_block_slice(&content, 0).expect("extract");
assert!(verify_block_slice(&slice, &address, 4096, 2).is_none());
}
#[test]
fn nonced_openings_roundtrip_every_block() {
for len in [1usize, 1024, 1025, 3000, 4096, 9001] {
let content = content_of(len);
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let count = block_count(len as u64);
for i in 0..count {
let siblings =
nonced_block_siblings(&NONCE, &PEER, &KEY, &content, i).expect("siblings");
let block = block_bytes(&content, i);
assert!(
verify_nonced_block(&NONCE, &PEER, &KEY, i, block, &siblings, &root, count),
"len {len} block {i} must verify"
);
}
}
}
#[test]
fn nonced_opening_rejects_wrong_block_bytes() {
let content = content_of(4096);
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 1).expect("siblings");
let mut wrong = block_bytes(&content, 1).to_vec();
wrong[0] ^= 0x01;
let bc = block_count(content.len() as u64);
assert!(!verify_nonced_block(
&NONCE, &PEER, &KEY, 1, &wrong, &siblings, &root, bc
));
}
#[test]
fn nonced_opening_binds_nonce_peer_and_key() {
let content = content_of(4096);
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 2).expect("siblings");
let block = block_bytes(&content, 2);
let bc = block_count(content.len() as u64);
assert!(verify_nonced_block(
&NONCE, &PEER, &KEY, 2, block, &siblings, &root, bc
));
let other = [0xAB; 32];
assert!(!verify_nonced_block(
&other, &PEER, &KEY, 2, block, &siblings, &root, bc
));
assert!(!verify_nonced_block(
&NONCE, &other, &KEY, 2, block, &siblings, &root, bc
));
assert!(!verify_nonced_block(
&NONCE, &PEER, &other, 2, block, &siblings, &root, bc
));
}
#[test]
fn leaf_is_keyed_by_the_nonce_not_prefixed() {
let block = content_of(1024);
let index = 3u32;
let block_len = block.len() as u32;
let got = nonced_block_leaf(&NONCE, &PEER, &KEY, index, &block);
let audit_key = nonced_block_key(&NONCE, &PEER, &KEY);
let mut keyed = blake3::Hasher::new_keyed(&audit_key);
keyed.update(DOMAIN_BLOCK_LEAF);
keyed.update(&index.to_le_bytes());
keyed.update(&block_len.to_le_bytes());
keyed.update(&block);
assert_eq!(
got,
*keyed.finalize().as_bytes(),
"leaf must be keyed BLAKE3 with the nonce-derived key"
);
let mut prefixed = blake3::Hasher::new();
prefixed.update(DOMAIN_BLOCK_LEAF);
prefixed.update(&NONCE);
prefixed.update(&PEER);
prefixed.update(&KEY);
prefixed.update(&index.to_le_bytes());
prefixed.update(&block_len.to_le_bytes());
prefixed.update(&block);
assert_ne!(
got,
*prefixed.finalize().as_bytes(),
"leaf must not use the precomputable prefixed-nonce construction"
);
}
#[test]
fn partial_holder_passes_on_kept_blocks_and_fails_on_dropped_ones() {
let content = content_of(8 * 1024); let count = block_count(content.len() as u64);
assert_eq!(count, 8);
let kept = 5u32;
let leaves: Vec<[u8; 32]> = (0..count)
.map(|i| {
if i < kept {
nonced_block_leaf(&NONCE, &PEER, &KEY, i, block_bytes(&content, i))
} else {
nonced_block_leaf(&NONCE, &PEER, &KEY, i, b"dropped")
}
})
.collect();
let mut level = leaves.clone();
while level.len() > 1 {
level = fold_level(&level);
}
let forged_root = level.first().copied().expect("non-empty tree");
for i in 0..kept {
let siblings = siblings_from_leaves(&leaves, i).expect("in range");
assert!(
verify_nonced_block(
&NONCE,
&PEER,
&KEY,
i,
block_bytes(&content, i),
&siblings,
&forged_root,
count,
),
"a kept block must verify — this is the false-pass path the docs describe"
);
}
for i in kept..count {
let siblings = siblings_from_leaves(&leaves, i).expect("in range");
assert!(
!verify_nonced_block(
&NONCE,
&PEER,
&KEY,
i,
block_bytes(&content, i),
&siblings,
&forged_root,
count,
),
"a dropped block must fail — sampling is what catches the partial holder"
);
}
}
#[test]
fn block_key_uses_the_subtree_domain_separated_derivation() {
let mut expected = blake3::Hasher::new_derive_key(BLOCK_KEY_CONTEXT);
expected.update(&NONCE);
expected.update(&PEER);
expected.update(&KEY);
assert_eq!(
nonced_block_key(&NONCE, &PEER, &KEY),
*expected.finalize().as_bytes(),
"block key must use derive_key mode"
);
let mut plain = blake3::Hasher::new();
plain.update(BLOCK_KEY_CONTEXT.as_bytes());
plain.update(&NONCE);
plain.update(&PEER);
plain.update(&KEY);
assert_ne!(
nonced_block_key(&NONCE, &PEER, &KEY),
*plain.finalize().as_bytes(),
"derive_key mode must not coincide with a plain domain-prefixed hash"
);
}
#[test]
fn nonced_root_changes_with_any_block_edit() {
let content = content_of(5000);
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let mut edited = content;
if let Some(b) = edited.last_mut() {
*b ^= 0x01;
}
let root2 = nonced_block_root(&NONCE, &PEER, &KEY, &edited);
assert_ne!(root, root2);
}
#[test]
fn nonced_siblings_out_of_range_is_none() {
let content = content_of(2048);
let count = block_count(content.len() as u64);
assert!(nonced_block_siblings(&NONCE, &PEER, &KEY, &content, count).is_none());
}
#[test]
fn relay_cannot_open_against_a_foreign_committed_root() {
let real = content_of(4096);
let garbage = content_of(4097); let foreign_root = nonced_block_root(&NONCE, &PEER, &KEY, &garbage);
let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &real, 0).expect("siblings");
let block = block_bytes(&real, 0);
assert!(!verify_nonced_block(
&NONCE,
&PEER,
&KEY,
0,
block,
&siblings,
&foreign_root,
block_count(real.len() as u64)
));
}
#[test]
fn canonical_depth_rejects_wrong_sibling_count() {
let content = content_of(4096); let bc = block_count(content.len() as u64);
assert_eq!(nonced_tree_depth(bc), 2);
let block0 = block_bytes(&content, 0);
let leaf0 = nonced_block_leaf(&NONCE, &PEER, &KEY, 0, block0);
assert!(!verify_nonced_block(
&NONCE,
&PEER,
&KEY,
0,
block0,
&[],
&leaf0,
bc
));
let root = nonced_block_root(&NONCE, &PEER, &KEY, &content);
let siblings = nonced_block_siblings(&NONCE, &PEER, &KEY, &content, 0).expect("siblings");
assert_eq!(siblings.len(), 2);
assert!(verify_nonced_block(
&NONCE, &PEER, &KEY, 0, block0, &siblings, &root, bc
));
let mut too_long = siblings;
too_long.push([0u8; 32]);
assert!(!verify_nonced_block(
&NONCE, &PEER, &KEY, 0, block0, &too_long, &root, bc
));
}
}