#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::missing_panics_doc,
clippy::cast_possible_truncation
)]
use std::sync::Arc;
use ant_node::replication::commitment_state::{BuiltCommitment, ResponderCommitmentState};
use ant_node::replication::config::{MAX_SLICE_OPENINGS, SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES};
use ant_node::replication::protocol::{
SubtreeAuditChallenge, SubtreeAuditResponse, SubtreeSliceChallenge, SubtreeSliceItem,
SubtreeSliceOpening, SubtreeSliceResponse,
};
use ant_node::replication::slice::{nonced_block_root, verify_block_slice, verify_nonced_block};
use ant_node::replication::storage_commitment_audit::{
handle_subtree_challenge, handle_subtree_challenge_measured, handle_subtree_slice_challenge,
};
use ant_node::replication::subtree::{verify_subtree_proof, StructureVerdict};
use ant_node::storage::{LmdbStorage, LmdbStorageConfig};
use saorsa_core::identity::PeerId;
use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey};
use tempfile::TempDir;
async fn test_storage() -> (LmdbStorage, TempDir) {
let temp_dir = TempDir::new().expect("create temp dir");
let config = LmdbStorageConfig {
root_dir: temp_dir.path().to_path_buf(),
..LmdbStorageConfig::test_default()
};
let storage = LmdbStorage::new(config).await.expect("create storage");
(storage, temp_dir)
}
fn keypair() -> (MlDsaPublicKey, MlDsaSecretKey) {
ml_dsa_65().generate_keypair().unwrap()
}
fn chunk_content(i: u8) -> Vec<u8> {
(0..1024u32).map(|n| (n as u8) ^ i).collect()
}
struct Responder {
peer_id: PeerId,
peer_id_bytes: [u8; 32],
state: Arc<ResponderCommitmentState>,
}
impl Responder {
async fn new(storage: &LmdbStorage, indices: &[u8]) -> Self {
let (pk, sk) = keypair();
let peer_id_bytes = *blake3::hash(&pk.to_bytes()).as_bytes();
let peer_id = PeerId::from_bytes(peer_id_bytes);
let mut entries = Vec::new();
for &i in indices {
let content = chunk_content(i);
let addr = LmdbStorage::compute_address(&content);
storage.put(&addr, &content).await.expect("put chunk");
let bytes_hash = *blake3::hash(&content).as_bytes();
entries.push((addr, bytes_hash));
}
let built =
BuiltCommitment::build(entries, &peer_id_bytes, &sk, &pk.to_bytes()).expect("build");
let state = Arc::new(ResponderCommitmentState::new());
state.rotate(built);
Self {
peer_id,
peer_id_bytes,
state,
}
}
fn current_hash(&self) -> [u8; 32] {
self.state.current().unwrap().hash()
}
fn address(i: u8) -> [u8; 32] {
LmdbStorage::compute_address(&chunk_content(i))
}
}
fn challenge_for(responder: &Responder, pin: [u8; 32], nonce: [u8; 32]) -> SubtreeAuditChallenge {
SubtreeAuditChallenge {
challenge_id: 42,
nonce,
challenged_peer_id: responder.peer_id_bytes,
expected_commitment_hash: pin,
}
}
#[tokio::test]
async fn honest_responder_answers_with_valid_proof() {
let (storage, _t) = test_storage().await;
let indices: Vec<u8> = (1..=64u8).collect();
let r = Responder::new(&storage, &indices).await;
let pin = r.current_hash();
let nonce = [0x11u8; 32];
let challenge = challenge_for(&r, pin, nonce);
let resp =
handle_subtree_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state)).await;
match resp {
SubtreeAuditResponse::Proof {
challenge_id,
commitment,
proof,
} => {
assert_eq!(challenge_id, 42);
assert_eq!(
ant_node::replication::commitment::commitment_hash(&commitment),
Some(pin),
);
assert_eq!(
verify_subtree_proof(&proof, &nonce, &commitment),
StructureVerdict::Valid,
"honest responder's proof must verify"
);
}
other => panic!("expected Proof, got {other:?}"),
}
}
#[tokio::test]
async fn bootstrapping_responder_reports_bootstrapping() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let challenge = challenge_for(&r, pin, [0x11u8; 32]);
let resp = handle_subtree_challenge(
&challenge,
&storage,
&r.peer_id,
true,
Some(&r.state),
)
.await;
assert!(
matches!(
resp,
SubtreeAuditResponse::Bootstrapping { challenge_id: 42 }
),
"expected Bootstrapping, got {resp:?}"
);
}
#[tokio::test]
async fn wrong_target_peer_is_rejected() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let mut challenge = challenge_for(&r, pin, [0x11u8; 32]);
challenge.challenged_peer_id = [0x99u8; 32];
let resp =
handle_subtree_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state)).await;
match resp {
SubtreeAuditResponse::Rejected {
challenge_id,
reason,
..
} => {
assert_eq!(challenge_id, 42);
assert!(
reason.contains("does not match this node"),
"expected wrong-peer rejection, got: {reason}"
);
}
other => panic!("expected Rejected(wrong peer), got {other:?}"),
}
}
#[tokio::test]
async fn unknown_pinned_hash_is_rejected() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let bogus_pin = [0x99u8; 32];
let challenge = challenge_for(&r, bogus_pin, [0x11u8; 32]);
let resp =
handle_subtree_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state)).await;
match resp {
SubtreeAuditResponse::Rejected { reason, .. } => {
assert!(
reason.contains("unknown commitment hash"),
"expected unknown-commitment-hash rejection, got: {reason}"
);
}
other => panic!("expected Rejected(unknown commitment hash), got {other:?}"),
}
}
#[tokio::test]
async fn missing_commitment_state_is_rejected() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let challenge = challenge_for(&r, pin, [0x11u8; 32]);
let resp = handle_subtree_challenge(&challenge, &storage, &r.peer_id, false, None).await;
assert!(
matches!(resp, SubtreeAuditResponse::Rejected { .. }),
"expected Rejected when no commitment state, got {resp:?}"
);
}
#[tokio::test]
async fn committed_key_with_missing_bytes_is_rejected() {
let (storage, _t) = test_storage().await;
let indices: Vec<u8> = (1..=32u8).collect();
let r = Responder::new(&storage, &indices).await;
let pin = r.current_hash();
for &i in &indices {
let addr = Responder::address(i);
storage.delete(&addr).await.expect("delete chunk");
}
let challenge = challenge_for(&r, pin, [0x11u8; 32]);
let resp =
handle_subtree_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state)).await;
match resp {
SubtreeAuditResponse::Rejected { reason, .. } => {
assert!(
reason.contains("missing bytes for committed key"),
"expected missing-bytes rejection, got: {reason}"
);
}
other => panic!("expected Rejected(missing bytes), got {other:?}"),
}
}
#[tokio::test]
async fn round1_proof_reports_the_content_it_read() {
let (storage, _t) = test_storage().await;
let indices: Vec<u8> = (1..=64u8).collect();
let r = Responder::new(&storage, &indices).await;
let challenge = challenge_for(&r, r.current_hash(), [0x11u8; 32]);
let work =
handle_subtree_challenge_measured(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
let SubtreeAuditResponse::Proof { ref proof, .. } = work.response else {
panic!("expected Proof, got {:?}", work.response);
};
let from_proof: i64 = proof
.leaves
.iter()
.map(|leaf| i64::from(leaf.content_len).max(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES))
.sum();
assert_eq!(
work.content_bytes, from_proof,
"reported work must equal the floored content the proof covers"
);
assert!(work.content_bytes > 0, "a real proof reads real bytes");
let unfloored: i64 = proof
.leaves
.iter()
.map(|leaf| i64::from(leaf.content_len))
.sum();
assert!(
work.content_bytes > unfloored,
"sub-floor records must not be charged at their byte count alone"
);
}
#[tokio::test]
async fn rejected_round1_still_reports_the_work_it_spent() {
let (storage, _t) = test_storage().await;
let indices: Vec<u8> = (1..=64u8).collect();
let r = Responder::new(&storage, &indices).await;
let pin = r.current_hash();
let challenge = challenge_for(&r, pin, [0x11u8; 32]);
let baseline =
handle_subtree_challenge_measured(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
let SubtreeAuditResponse::Proof { ref proof, .. } = baseline.response else {
panic!("expected a baseline Proof, got {:?}", baseline.response);
};
assert!(
proof.leaves.len() > 1,
"need a multi-leaf subtree for partial work to exist; got {}",
proof.leaves.len()
);
let last_leaf = proof.leaves.last().expect("non-empty");
let last_leaf_charge = i64::from(last_leaf.content_len);
let deleted_len = (last_leaf_charge - SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES).max(0);
let last = last_leaf.key;
let baseline_bytes = baseline.content_bytes;
storage.delete(&last).await.expect("delete last leaf chunk");
let work =
handle_subtree_challenge_measured(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match work.response {
SubtreeAuditResponse::Rejected { ref reason, .. } => {
assert!(
reason.contains("missing bytes for committed key"),
"expected the missing-bytes rejection, got: {reason}"
);
}
ref other => panic!("expected Rejected(missing bytes), got {other:?}"),
}
assert!(
work.content_bytes > 0,
"the leaves read before the hole must be charged, not written off"
);
assert_eq!(
work.content_bytes,
baseline_bytes - deleted_len,
"charge must cover every leaf attempted, at the floor for the failed one"
);
}
#[tokio::test]
async fn a_round1_failing_on_its_first_leaf_still_reports_the_attempt() {
let (storage, _t) = test_storage().await;
let indices: Vec<u8> = (1..=64u8).collect();
let r = Responder::new(&storage, &indices).await;
let pin = r.current_hash();
let challenge = challenge_for(&r, pin, [0x11u8; 32]);
let baseline =
handle_subtree_challenge_measured(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
let SubtreeAuditResponse::Proof { ref proof, .. } = baseline.response else {
panic!("expected a baseline Proof, got {:?}", baseline.response);
};
let first = proof.leaves.first().expect("non-empty").key;
storage
.delete(&first)
.await
.expect("delete first leaf chunk");
let work =
handle_subtree_challenge_measured(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match work.response {
SubtreeAuditResponse::Rejected { ref reason, .. } => {
assert!(
reason.contains("missing bytes for committed key"),
"expected the missing-bytes rejection, got: {reason}"
);
}
ref other => panic!("expected Rejected(missing bytes), got {other:?}"),
}
assert_eq!(
work.content_bytes, SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES,
"a first-leaf failure must cost the attempt, and exactly the attempt"
);
}
#[tokio::test]
async fn slice_challenge_opens_valid_blocks_for_committed_keys() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let nonce = [0x22u8; 32];
let openings = vec![
SubtreeSliceOpening {
key: Responder::address(1),
block_index: 0,
},
SubtreeSliceOpening {
key: Responder::address(2),
block_index: 0,
},
];
let challenge = SubtreeSliceChallenge {
challenge_id: 43,
nonce,
challenged_peer_id: r.peer_id_bytes,
expected_commitment_hash: pin,
openings: openings.clone(),
};
let resp =
handle_subtree_slice_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match resp {
SubtreeSliceResponse::Items {
challenge_id,
items,
} => {
assert_eq!(challenge_id, 43);
assert_eq!(
items.len(),
openings.len(),
"one item per requested opening"
);
for (item, (i, opening)) in items.iter().zip([1u8, 2].into_iter().zip(openings)) {
match item {
SubtreeSliceItem::Present {
key: k,
block_index,
bao_slice,
nonced_siblings,
} => {
assert_eq!(*k, opening.key);
assert_eq!(*block_index, 0);
let content = chunk_content(i);
let bytes_hash = *blake3::hash(&content).as_bytes();
let block =
verify_block_slice(bao_slice, &bytes_hash, content.len() as u64, 0)
.expect("bao slice must verify against the chunk address");
assert_eq!(block, content, "opened block must be the ORIGINAL bytes");
let root =
nonced_block_root(&nonce, &r.peer_id_bytes, &opening.key, &content);
assert!(
verify_nonced_block(
&nonce,
&r.peer_id_bytes,
&opening.key,
0,
&block,
nonced_siblings,
&root,
ant_node::replication::slice::block_count(content.len() as u64),
),
"nonced opening must fold to the honest nonced root"
);
}
other @ SubtreeSliceItem::Absent { .. } => {
panic!("expected Present for stored committed key, got {other:?}")
}
}
}
}
other => panic!("expected Items, got {other:?}"),
}
}
#[tokio::test]
async fn slice_challenge_coalesces_duplicate_and_interleaved_openings() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let nonce = [0x55u8; 32];
let k1 = Responder::address(1);
let k2 = Responder::address(2);
let openings = vec![
SubtreeSliceOpening {
key: k1,
block_index: 0,
},
SubtreeSliceOpening {
key: k2,
block_index: 0,
},
SubtreeSliceOpening {
key: k1,
block_index: 0,
},
SubtreeSliceOpening {
key: k2,
block_index: 0,
},
SubtreeSliceOpening {
key: k1,
block_index: 0,
},
];
assert!(openings.len() <= MAX_SLICE_OPENINGS);
let challenge = SubtreeSliceChallenge {
challenge_id: 46,
nonce,
challenged_peer_id: r.peer_id_bytes,
expected_commitment_hash: pin,
openings,
};
let resp =
handle_subtree_slice_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match resp {
SubtreeSliceResponse::Items {
challenge_id,
items,
} => {
assert_eq!(challenge_id, 46);
assert_eq!(
items.len(),
2,
"duplicate openings must not multiply response items"
);
let mut seen: Vec<([u8; 32], u32)> = Vec::new();
for item in &items {
match item {
SubtreeSliceItem::Present {
key, block_index, ..
} => {
assert!(
!seen.contains(&(*key, *block_index)),
"each (key, block) identity must appear at most once"
);
seen.push((*key, *block_index));
}
other @ SubtreeSliceItem::Absent { .. } => {
panic!("expected Present for a stored committed key, got {other:?}")
}
}
}
seen.sort_unstable();
let mut want = vec![(k1, 0u32), (k2, 0u32)];
want.sort_unstable();
assert_eq!(
seen, want,
"both distinct openings must be served exactly once, order-independent"
);
}
other => panic!("expected Items, got {other:?}"),
}
}
#[tokio::test]
async fn slice_challenge_opens_a_deep_block_of_a_large_chunk() {
use ant_node::replication::commitment::commitment_hash;
use ant_node::replication::slice::block_count;
let (storage, _t) = test_storage().await;
let content: Vec<u8> = (0..100_000u32)
.map(|n| (n.wrapping_mul(2_654_435_761) >> 13) as u8)
.collect();
let addr = LmdbStorage::compute_address(&content);
storage.put(&addr, &content).await.expect("put chunk");
let bytes_hash = *blake3::hash(&content).as_bytes();
let (pk, sk) = keypair();
let peer_id_bytes = *blake3::hash(&pk.to_bytes()).as_bytes();
let peer_id = PeerId::from_bytes(peer_id_bytes);
let built = BuiltCommitment::build(
vec![(addr, bytes_hash)],
&peer_id_bytes,
&sk,
&pk.to_bytes(),
)
.expect("build");
let pin = commitment_hash(built.commitment()).unwrap();
let state = Arc::new(ResponderCommitmentState::new());
state.rotate(built);
let count = block_count(content.len() as u64);
assert!(
count > 64,
"test needs a genuinely multi-block chunk, got {count} blocks"
);
let block_index = 50u32;
let nonce = [0x5Au8; 32];
let challenge = SubtreeSliceChallenge {
challenge_id: 77,
nonce,
challenged_peer_id: peer_id_bytes,
expected_commitment_hash: pin,
openings: vec![SubtreeSliceOpening {
key: addr,
block_index,
}],
};
let resp =
handle_subtree_slice_challenge(&challenge, &storage, &peer_id, false, Some(&state)).await;
let SubtreeSliceResponse::Items { items, .. } = resp else {
panic!("expected Items, got {resp:?}");
};
let Some(SubtreeSliceItem::Present {
block_index: bi,
bao_slice,
nonced_siblings,
..
}) = items.first()
else {
panic!("expected a single Present opening, got {items:?}");
};
assert_eq!(*bi, block_index);
let block = verify_block_slice(bao_slice, &bytes_hash, content.len() as u64, block_index)
.expect("deep-block bao slice must verify");
let start = block_index as usize * 1024;
assert_eq!(
block,
content[start..start + 1024],
"opened block must be block 50's bytes"
);
let root = nonced_block_root(&nonce, &peer_id_bytes, &addr, &content);
assert!(
verify_nonced_block(
&nonce,
&peer_id_bytes,
&addr,
block_index,
&block,
nonced_siblings,
&root,
ant_node::replication::slice::block_count(content.len() as u64)
),
"deep-block nonced opening must fold to the honest root"
);
assert!(
bao_slice.len() < content.len() / 4,
"the slice ({} bytes) must be far smaller than the chunk ({} bytes)",
bao_slice.len(),
content.len()
);
}
#[tokio::test]
async fn oversize_slice_challenge_is_rejected() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let openings: Vec<SubtreeSliceOpening> = (0..=MAX_SLICE_OPENINGS)
.map(|i| SubtreeSliceOpening {
key: [u8::try_from(i % 251).unwrap_or(0); 32],
block_index: 0,
})
.collect();
assert!(openings.len() > MAX_SLICE_OPENINGS);
let challenge = SubtreeSliceChallenge {
challenge_id: 44,
nonce: [0x33u8; 32],
challenged_peer_id: r.peer_id_bytes,
expected_commitment_hash: pin,
openings,
};
let resp =
handle_subtree_slice_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match resp {
SubtreeSliceResponse::Rejected { reason, .. } => {
assert!(
reason.contains("max"),
"expected per-challenge openings-cap rejection, got: {reason}"
);
}
other => panic!("expected Rejected(oversize), got {other:?}"),
}
}
#[tokio::test]
async fn slice_challenge_with_too_many_distinct_keys_is_rejected() {
let (storage, _t) = test_storage().await;
let r = Responder::new(&storage, &[1, 2, 3, 4]).await;
let pin = r.current_hash();
let openings: Vec<SubtreeSliceOpening> = (0..6u8)
.map(|i| SubtreeSliceOpening {
key: [i + 1; 32],
block_index: 0,
})
.collect();
assert!(openings.len() <= MAX_SLICE_OPENINGS);
let challenge = SubtreeSliceChallenge {
challenge_id: 45,
nonce: [0x44u8; 32],
challenged_peer_id: r.peer_id_bytes,
expected_commitment_hash: pin,
openings,
};
let resp =
handle_subtree_slice_challenge(&challenge, &storage, &r.peer_id, false, Some(&r.state))
.await;
match resp {
SubtreeSliceResponse::Rejected { reason, .. } => {
assert!(
reason.contains("distinct keys"),
"expected distinct-key rejection, got: {reason}"
);
}
other => panic!("expected Rejected(distinct keys), got {other:?}"),
}
}