cycles-quartz/utils/cw-proof/src/verifier/ics23.rs

68 lines
1.6 KiB
Rust
Raw Normal View History

2023-12-30 20:33:51 +00:00
use alloc::vec::Vec;
2023-12-30 12:56:07 +00:00
use core::marker::PhantomData;
use ics23::{
calculate_existence_root, commitment_proof::Proof, verify_membership, CommitmentProof,
ProofSpec,
};
2023-12-30 21:42:30 +00:00
use crate::error::ProofError;
2023-12-30 12:56:07 +00:00
use crate::verifier::Verifier;
2023-12-30 12:50:47 +00:00
#[derive(Clone, Debug)]
2023-12-31 11:42:54 +00:00
pub struct Ics23MembershipVerifier<K, V> {
2023-12-30 12:50:47 +00:00
spec: ProofSpec,
2023-12-31 11:42:54 +00:00
_phantom: PhantomData<(K, V)>,
2023-12-30 12:50:47 +00:00
}
2023-12-31 11:42:54 +00:00
impl<K, V> Ics23MembershipVerifier<K, V> {
2023-12-30 12:50:47 +00:00
pub fn new(spec: ProofSpec) -> Self {
Self {
spec,
_phantom: Default::default(),
}
}
}
2023-12-31 11:42:54 +00:00
impl<K, V> Verifier for Ics23MembershipVerifier<K, V>
2023-12-30 12:50:47 +00:00
where
K: AsRef<[u8]>,
2023-12-31 11:42:54 +00:00
V: AsRef<[u8]>,
2023-12-30 12:50:47 +00:00
{
type Proof = CommitmentProof;
type Root = Vec<u8>;
type Key = K;
2023-12-31 11:42:54 +00:00
type Value = V;
2023-12-30 12:50:47 +00:00
type Error = ProofError;
fn verify(
&self,
commitment_proof: &Self::Proof,
key: &Self::Key,
2023-12-31 11:42:54 +00:00
value: &Self::Value,
2023-12-30 12:50:47 +00:00
) -> Result<Self::Root, Self::Error> {
if value.as_ref().is_empty() {
2023-12-30 21:42:30 +00:00
return Err(ProofError::EmptyVerifiedValue);
2023-12-30 12:50:47 +00:00
}
let Some(Proof::Exist(existence_proof)) = &commitment_proof.proof else {
2023-12-30 21:42:30 +00:00
return Err(ProofError::InvalidMerkleProof);
2023-12-30 12:50:47 +00:00
};
let root = calculate_existence_root::<ics23::HostFunctionsManager>(existence_proof)
2023-12-30 21:42:30 +00:00
.map_err(|_| ProofError::InvalidMerkleProof)?;
2023-12-30 12:50:47 +00:00
if !verify_membership::<ics23::HostFunctionsManager>(
commitment_proof,
&self.spec,
&root,
key.as_ref(),
2023-12-31 11:42:54 +00:00
value.as_ref(),
2023-12-30 12:50:47 +00:00
) {
2023-12-30 21:42:30 +00:00
return Err(ProofError::VerificationFailure);
2023-12-30 12:50:47 +00:00
}
Ok(root)
}
}