use crate::sign::secp256k1;
#[cfg(feature = "tracing")]
use essential_hash::content_addr;
use essential_types::{contract, predicate::Predicate};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum InvalidSignedContract {
#[error("invalid signature: {0}")]
Signature(#[from] secp256k1::Error),
#[error("invalid contract: {0}")]
Set(#[from] InvalidContract),
}
#[derive(Debug, Error)]
pub enum InvalidContract {
#[error("the number of predicates ({0}) exceeds the limit ({MAX_PREDICATES})")]
TooManyPredicates(usize),
#[error("predicate at index {0} is invalid: {1}")]
Predicate(usize, InvalidPredicate),
}
#[derive(Debug, Error)]
pub enum InvalidPredicate {
#[error(
"the number of nodes ({0}) exceeds the limit ({})",
Predicate::MAX_NODES
)]
TooManyNodes(usize),
#[error(
"the number of edges ({0}) exceeds the limit ({})",
Predicate::MAX_EDGES
)]
TooManyEdges(usize),
}
pub const MAX_PREDICATES: usize = 100;
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all, fields(addr = %content_addr(&signed_contract.contract)), err))]
pub fn check_signed_contract(
signed_contract: &contract::SignedContract,
) -> Result<(), InvalidSignedContract> {
essential_sign::contract::verify(signed_contract)?;
check_contract(signed_contract.contract.as_ref())?;
Ok(())
}
pub fn check_contract(predicates: &[Predicate]) -> Result<(), InvalidContract> {
if predicates.len() > MAX_PREDICATES {
return Err(InvalidContract::TooManyPredicates(predicates.len()));
}
for (ix, predicate) in predicates.iter().enumerate() {
check(predicate).map_err(|e| InvalidContract::Predicate(ix, e))?;
}
Ok(())
}
pub fn check(predicate: &Predicate) -> Result<(), InvalidPredicate> {
if predicate.nodes.len() > Predicate::MAX_NODES.into() {
return Err(InvalidPredicate::TooManyNodes(predicate.nodes.len()));
}
if predicate.edges.len() > Predicate::MAX_EDGES.into() {
return Err(InvalidPredicate::TooManyEdges(predicate.edges.len()));
}
Ok(())
}