use akd_core::configuration::Configuration;
use akd_core::AzksElement;
use crate::append_only_zks::AzksParallelismConfig;
use crate::AzksValue;
use crate::{
append_only_zks::InsertMode,
errors::{AkdError, AuditorError, AzksError},
storage::{manager::StorageManager, memory::AsyncInMemoryDatabase},
AppendOnlyProof, Azks, Digest, SingleAppendOnlyProof,
};
#[cfg_attr(feature = "tracing_instrument", tracing::instrument(skip_all))]
pub async fn audit_verify<TC: Configuration>(
hashes: Vec<Digest>,
proof: AppendOnlyProof,
) -> Result<(), AkdError> {
if proof.epochs.len() + 1 != hashes.len() {
return Err(AkdError::AuditErr(AuditorError::VerifyAuditProof(format!(
"The proof has a different number of epochs than needed for hashes.
The number of hashes you provide should be one more than the number of epochs!
Number of epochs = {}, number of hashes = {}",
proof.epochs.len(),
hashes.len()
))));
}
if proof.epochs.len() != proof.proofs.len() {
return Err(AkdError::AuditErr(AuditorError::VerifyAuditProof(format!(
"The proof has {} epochs and {} proofs. These should be equal!",
proof.epochs.len(),
proof.proofs.len()
))));
}
for i in 0..hashes.len() - 1 {
let start_hash = hashes[i];
let end_hash = hashes[i + 1];
verify_consecutive_append_only::<TC>(
&proof.proofs[i],
start_hash,
end_hash,
proof.epochs[i] + 1,
)
.await?;
}
Ok(())
}
#[cfg_attr(feature = "tracing_instrument", tracing::instrument(skip_all))]
pub async fn verify_consecutive_append_only<TC: Configuration>(
proof: &SingleAppendOnlyProof,
start_hash: Digest,
end_hash: Digest,
end_epoch: u64,
) -> Result<(), AkdError> {
verify_append_only_hash::<TC>(proof.unchanged_nodes.clone(), start_hash, None).await?;
let mut unchanged_with_inserted_nodes = proof.unchanged_nodes.clone();
unchanged_with_inserted_nodes.extend(proof.inserted.iter().map(|x| {
let mut y = *x;
y.value = AzksValue(TC::hash_leaf_with_commitment(x.value, end_epoch).0);
y
}));
verify_append_only_hash::<TC>(unchanged_with_inserted_nodes, end_hash, Some(end_epoch - 1))
.await?;
Ok(())
}
async fn verify_append_only_hash<TC: Configuration>(
nodes: Vec<AzksElement>,
expected_hash: Digest,
latest_epoch: Option<u64>,
) -> Result<(), AkdError> {
let manager = StorageManager::new_no_cache(
AsyncInMemoryDatabase::new_with_remove_child_nodes_on_insertion(),
);
let mut azks = Azks::new::<TC, _>(&manager).await?;
if let Some(epoch) = latest_epoch {
azks.latest_epoch = epoch;
}
azks.batch_insert_nodes::<TC, _>(
&manager,
nodes,
InsertMode::Auditor,
AzksParallelismConfig::default(),
)
.await?;
let computed_hash: Digest = azks.get_root_hash::<TC, _>(&manager).await?;
if computed_hash != expected_hash {
return Err(AkdError::AzksErr(AzksError::VerifyAppendOnlyProof(
format!(
"Expected hash {} does not match computed root hash {}",
hex::encode(expected_hash),
hex::encode(computed_hash)
),
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::client::verify_membership_for_tests_only;
use crate::test_config;
use crate::{
AzksValue, Direction, MembershipProof, NodeLabel, SiblingProof, SingleAppendOnlyProof,
};
test_config!(test_auditor_rejects_prefix_collision_value_rewrite);
#[allow(non_snake_case)]
async fn test_auditor_rejects_prefix_collision_value_rewrite<TC: Configuration>(
) -> Result<(), AkdError> {
const AUDIT_EPOCH: u64 = 2;
const START_EPOCH: u64 = AUDIT_EPOCH - 1;
let shell_label = NodeLabel::new([0u8; 32], 1);
let label = NodeLabel::new([0u8; 32], 256);
let empty_child = AzksElement {
label: TC::empty_label(),
value: TC::empty_node_hash(),
};
let parent_hash = |child_label: NodeLabel, child_val: AzksValue| {
TC::compute_parent_hash_from_children(
&child_val,
&child_label.value::<TC>(),
&empty_child.value,
&empty_child.label.value::<TC>(),
)
};
let val1 = AzksValue(TC::hash(b"val1"));
let val2 = AzksValue(TC::hash(b"val2"));
let leaf_val1 = AzksValue(TC::hash_leaf_with_commitment(val1, START_EPOCH).0);
let leaf_val2 = AzksValue(TC::hash_leaf_with_commitment(val2, AUDIT_EPOCH).0);
let shell_val = parent_hash(label, leaf_val1);
let root_hash1 = TC::compute_root_hash_from_val(&parent_hash(shell_label, shell_val));
let root_hash2 = TC::compute_root_hash_from_val(&parent_hash(
shell_label,
parent_hash(label, leaf_val2),
));
let update_proof = SingleAppendOnlyProof {
unchanged_nodes: vec![AzksElement {
label: shell_label,
value: shell_val,
}],
inserted: vec![AzksElement { label, value: val2 }],
};
let sibling_path = vec![
SiblingProof {
label: NodeLabel::root(),
siblings: [empty_child],
direction: Direction::Left,
},
SiblingProof {
label: shell_label,
siblings: [empty_child],
direction: Direction::Left,
},
];
let membership = |hash_val| MembershipProof {
label,
hash_val,
sibling_proofs: sibling_path.clone(),
};
verify_membership_for_tests_only::<TC>(root_hash1, &membership(leaf_val1)).unwrap();
verify_membership_for_tests_only::<TC>(root_hash2, &membership(leaf_val2)).unwrap();
assert_ne!(leaf_val1, leaf_val2);
let result = audit_verify::<TC>(
vec![root_hash1, root_hash2],
AppendOnlyProof {
proofs: vec![update_proof],
epochs: vec![START_EPOCH],
},
)
.await;
assert!(
matches!(
result,
Err(AkdError::AzksErr(AzksError::BatchInsertDroppedNode(_)))
),
"auditor must reject the value-rewrite transition, got {result:?}"
);
Ok(())
}
}