#[cfg(test)]
mod tests;
pub use crate::work_budget::BudgetError;
use crate::work_budget::WorkBucket;
use ic_auth_protocol_types::PortableMechanism;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "receiver-stable",
derive(serde::Serialize, serde::Deserialize)
)]
pub struct VerificationCosts {
pub ed25519: u32,
pub certified: u32,
}
#[derive(Debug, Eq, PartialEq)]
pub struct VerificationBudget {
bucket: WorkBucket,
costs: VerificationCosts,
}
#[cfg(feature = "receiver-stable")]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(remote = "VerificationBudget")]
pub(crate) struct RetainedBudget {
bucket: WorkBucket,
costs: VerificationCosts,
}
impl VerificationBudget {
#[cfg(feature = "receiver-stable")]
pub(crate) fn matches(
&self,
costs: VerificationCosts,
capacity: u32,
interval: u64,
now: u64,
) -> bool {
self.costs == costs && self.bucket.matches(capacity, interval, now)
}
pub fn new(
capacity: u32,
interval_ns: u64,
costs: VerificationCosts,
now_ns: u64,
) -> Result<Self, BudgetError> {
if costs.ed25519 == 0
|| costs.certified == 0
|| costs.ed25519 > capacity
|| costs.certified > capacity
{
return Err(BudgetError::InvalidPolicy);
}
Ok(Self {
bucket: WorkBucket::new(capacity, interval_ns, now_ns)?,
costs,
})
}
#[must_use]
pub const fn available(&self) -> u32 {
self.bucket.available()
}
#[must_use]
pub const fn observed_at_ns(&self) -> u64 {
self.bucket.observed_at_ns()
}
pub(super) fn charge(
&mut self,
now_ns: u64,
mechanism: PortableMechanism,
) -> Result<(), BudgetError> {
let cost = match mechanism {
PortableMechanism::Ed25519 => self.costs.ed25519,
PortableMechanism::Certified => self.costs.certified,
};
self.bucket.charge(now_ns, cost)
}
}