use crate::error::{ContractRuntimeError, Result};
use crate::types::CircuitId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CostVector {
pub read_time_ps: u64,
pub compute_time_ps: u64,
pub block_usage: u64,
pub bytes_written: u64,
pub bytes_churned: u64,
}
impl CostVector {
pub const ZERO: Self = Self {
read_time_ps: 0,
compute_time_ps: 0,
block_usage: 0,
bytes_written: 0,
bytes_churned: 0,
};
pub const UNBOUNDED: Self = Self {
read_time_ps: u64::MAX,
compute_time_ps: u64::MAX,
block_usage: u64::MAX,
bytes_written: u64::MAX,
bytes_churned: u64::MAX,
};
fn dimensions(self) -> [(&'static str, u64); 5] {
[
("read time (ps)", self.read_time_ps),
("compute time (ps)", self.compute_time_ps),
("block usage (bytes)", self.block_usage),
("bytes written", self.bytes_written),
("bytes churned", self.bytes_churned),
]
}
#[must_use]
pub fn saturating_add(self, other: Self) -> Self {
Self {
read_time_ps: self.read_time_ps.saturating_add(other.read_time_ps),
compute_time_ps: self.compute_time_ps.saturating_add(other.compute_time_ps),
block_usage: self.block_usage.saturating_add(other.block_usage),
bytes_written: self.bytes_written.saturating_add(other.bytes_written),
bytes_churned: self.bytes_churned.saturating_add(other.bytes_churned),
}
}
#[must_use]
pub fn saturating_sub(self, other: Self) -> Self {
Self {
read_time_ps: self.read_time_ps.saturating_sub(other.read_time_ps),
compute_time_ps: self.compute_time_ps.saturating_sub(other.compute_time_ps),
block_usage: self.block_usage.saturating_sub(other.block_usage),
bytes_written: self.bytes_written.saturating_sub(other.bytes_written),
bytes_churned: self.bytes_churned.saturating_sub(other.bytes_churned),
}
}
#[must_use]
pub fn fits_within(self, capacity: Self) -> bool {
self.first_excess(capacity).is_none()
}
#[must_use]
pub fn first_excess(self, capacity: Self) -> Option<(&'static str, u64, u64)> {
self.dimensions()
.into_iter()
.zip(capacity.dimensions())
.find(|((_, used), (_, cap))| used > cap)
.map(|((name, used), (_, cap))| (name, used, cap))
}
fn dominant_share(self, capacity: Self) -> Share {
self.dimensions()
.into_iter()
.zip(capacity.dimensions())
.map(|((_, used), (_, cap))| Share::new(u128::from(used), u128::from(cap)))
.fold(Share::ZERO, Share::max)
}
}
#[derive(Debug, Clone, Copy)]
struct Share {
used: u128,
capacity: u128,
}
impl Share {
const ZERO: Self = Self {
used: 0,
capacity: 1,
};
fn new(used: u128, capacity: u128) -> Self {
if used == 0 {
Self::ZERO
} else {
Self { used, capacity }
}
}
fn max(self, other: Self) -> Self {
if self.cmp(&other).is_lt() {
other
} else {
self
}
}
}
impl PartialEq for Share {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl Eq for Share {}
impl PartialOrd for Share {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Share {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(self.used * other.capacity).cmp(&(other.used * self.capacity))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CircuitWeight {
pub id: CircuitId,
pub vk_bytes: usize,
pub deploy_cost: CostVector,
pub maintenance_cost: CostVector,
}
#[derive(Debug, Clone, Copy)]
pub struct PackBudget {
pub max_tx_bytes: usize,
pub deploy_overhead: usize,
pub maintenance_overhead: usize,
pub max_cost: CostVector,
pub deploy_overhead_cost: CostVector,
pub maintenance_overhead_cost: CostVector,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeployPlan {
pub deploy_batch: Vec<CircuitId>,
pub maintenance_batches: Vec<Vec<CircuitId>>,
}
impl DeployPlan {
#[must_use]
pub fn total_circuits(&self) -> usize {
self.deploy_batch.len() + self.maintenance_batches.iter().map(Vec::len).sum::<usize>()
}
#[must_use]
pub fn total_transactions(&self) -> usize {
1 + self.maintenance_batches.len()
}
#[must_use]
pub fn is_single_shot(&self) -> bool {
self.maintenance_batches.is_empty()
}
}
#[derive(Clone, Copy)]
struct Load {
bytes: usize,
cost: CostVector,
}
impl Load {
fn plus(self, bytes: usize, cost: CostVector) -> Self {
Self {
bytes: self.bytes.saturating_add(bytes),
cost: self.cost.saturating_add(cost),
}
}
fn fits(self, budget: &PackBudget) -> bool {
self.bytes <= budget.max_tx_bytes && self.cost.fits_within(budget.max_cost)
}
}
pub fn plan_incremental_deploy(
circuits: &[CircuitWeight],
budget: &PackBudget,
) -> Result<DeployPlan> {
let maint_cap = budget
.max_tx_bytes
.checked_sub(budget.maintenance_overhead)
.filter(|c| *c > 0)
.ok_or_else(|| ContractRuntimeError::Provider {
provider: "plan_incremental_deploy",
message: format!(
"max_tx_bytes ({}) is not larger than the maintenance-tx overhead ({}); \
raise --max-tx-bytes",
budget.max_tx_bytes, budget.maintenance_overhead,
),
})?;
let maintenance_empty = Load {
bytes: budget.maintenance_overhead,
cost: budget.maintenance_overhead_cost,
};
check_feasible(circuits, budget, maint_cap)?;
let weight = |w: &CircuitWeight| {
Share::new(w.vk_bytes as u128, maint_cap as u128)
.max(w.maintenance_cost.dominant_share(budget.max_cost))
};
let mut sorted: Vec<&CircuitWeight> = circuits.iter().collect();
sorted.sort_by(|a, b| {
weight(b)
.cmp(&weight(a))
.then_with(|| a.id.as_str().cmp(b.id.as_str()))
});
let mut deploy_batch: Vec<CircuitId> = Vec::new();
let mut deploy_load = Load {
bytes: budget.deploy_overhead,
cost: budget.deploy_overhead_cost,
};
let mut remaining: Vec<&CircuitWeight> = Vec::new();
for w in sorted {
let with = deploy_load.plus(w.vk_bytes, w.deploy_cost);
if with.fits(budget) {
deploy_load = with;
deploy_batch.push(w.id.clone());
} else {
remaining.push(w);
}
}
let mut bins: Vec<(Load, Vec<CircuitId>)> = Vec::new();
for w in remaining {
match bins
.iter_mut()
.find(|(load, _)| load.plus(w.vk_bytes, w.maintenance_cost).fits(budget))
{
Some((load, ids)) => {
*load = load.plus(w.vk_bytes, w.maintenance_cost);
ids.push(w.id.clone());
}
None => bins.push((
maintenance_empty.plus(w.vk_bytes, w.maintenance_cost),
vec![w.id.clone()],
)),
}
}
Ok(DeployPlan {
deploy_batch,
maintenance_batches: bins.into_iter().map(|(_, ids)| ids).collect(),
})
}
fn check_feasible(circuits: &[CircuitWeight], budget: &PackBudget, maint_cap: usize) -> Result<()> {
for (kind, overhead) in [
("deploy", budget.deploy_overhead_cost),
("maintenance", budget.maintenance_overhead_cost),
] {
if let Some((dimension, used, cap)) = overhead.first_excess(budget.max_cost) {
return Err(ContractRuntimeError::Provider {
provider: "plan_incremental_deploy",
message: format!(
"an empty {kind} transaction already needs {used} {dimension}, over the \
per-transaction limit of {cap}"
),
});
}
}
for w in circuits {
if w.vk_bytes > maint_cap {
return Err(ContractRuntimeError::Provider {
provider: "plan_incremental_deploy",
message: format!(
"circuit '{}' has a {}-byte verifier key, larger than the per-transaction \
capacity of {maint_cap} bytes at max_tx_bytes={}; this circuit cannot be \
deployed at this budget — raise --max-tx-bytes",
w.id.as_str(),
w.vk_bytes,
budget.max_tx_bytes,
),
});
}
let alone = budget
.maintenance_overhead_cost
.saturating_add(w.maintenance_cost);
if let Some((dimension, used, cap)) = alone.first_excess(budget.max_cost) {
return Err(ContractRuntimeError::Provider {
provider: "plan_incremental_deploy",
message: format!(
"circuit '{}' alone needs {used} {dimension} in a maintenance transaction, \
over the per-transaction limit of {cap}; this circuit cannot be deployed",
w.id.as_str(),
),
});
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn w(id: &str, vk_bytes: usize) -> CircuitWeight {
CircuitWeight {
id: CircuitId::new(id),
vk_bytes,
deploy_cost: CostVector::ZERO,
maintenance_cost: CostVector::ZERO,
}
}
fn budget(max: usize, deploy_oh: usize, maint_oh: usize) -> PackBudget {
PackBudget {
max_tx_bytes: max,
deploy_overhead: deploy_oh,
maintenance_overhead: maint_oh,
max_cost: CostVector::UNBOUNDED,
deploy_overhead_cost: CostVector::ZERO,
maintenance_overhead_cost: CostVector::ZERO,
}
}
fn assert_within_budget(plan: &DeployPlan, circuits: &[CircuitWeight], b: &PackBudget) {
let size = |id: &CircuitId| circuits.iter().find(|c| &c.id == id).unwrap().vk_bytes;
let deploy_sum: usize = plan.deploy_batch.iter().map(&size).sum();
assert!(
deploy_sum + b.deploy_overhead <= b.max_tx_bytes,
"deploy batch {deploy_sum}+{} over {}",
b.deploy_overhead,
b.max_tx_bytes
);
for batch in &plan.maintenance_batches {
let s: usize = batch.iter().map(&size).sum();
assert!(
s + b.maintenance_overhead <= b.max_tx_bytes,
"maintenance batch {s}+{} over {}",
b.maintenance_overhead,
b.max_tx_bytes
);
}
}
#[test]
fn everything_fits_in_one_deploy_when_budget_is_large() {
let circuits = vec![w("a", 1000), w("b", 1000), w("c", 1000)];
let b = budget(1_000_000, 5000, 2000);
let plan = plan_incremental_deploy(&circuits, &b).unwrap();
assert!(plan.is_single_shot());
assert_eq!(plan.deploy_batch.len(), 3);
assert_eq!(plan.total_transactions(), 1);
assert_eq!(plan.total_circuits(), 3);
}
#[test]
fn splits_across_deploy_and_maintenance_when_over_budget() {
let circuits = vec![w("a", 1000), w("b", 1000), w("c", 1000), w("d", 1000)];
let b = budget(2000, 800, 100);
let plan = plan_incremental_deploy(&circuits, &b).unwrap();
assert_eq!(plan.deploy_batch.len(), 1);
assert_eq!(plan.maintenance_batches.len(), 3);
assert_eq!(plan.total_circuits(), 4);
assert_within_budget(&plan, &circuits, &b);
}
#[test]
fn packs_multiple_small_circuits_per_maintenance_batch() {
let circuits: Vec<_> = (0..10).map(|i| w(&format!("c{i:02}"), 100)).collect();
let b = budget(1000, 950, 100);
let plan = plan_incremental_deploy(&circuits, &b).unwrap();
assert_eq!(plan.deploy_batch, [] as [CircuitId; 0]);
assert_eq!(plan.total_circuits(), 10);
assert_eq!(plan.maintenance_batches.len(), 2);
assert_within_budget(&plan, &circuits, &b);
}
#[test]
fn deploy_batch_packs_largest_first() {
let circuits = vec![w("small", 100), w("big", 1000), w("mid", 500)];
let b = budget(2000, 500, 100);
let plan = plan_incremental_deploy(&circuits, &b).unwrap();
assert!(plan.deploy_batch.contains(&CircuitId::new("big")));
assert!(plan.deploy_batch.contains(&CircuitId::new("mid")));
assert_within_budget(&plan, &circuits, &b);
}
#[test]
fn errors_when_a_single_vk_exceeds_capacity() {
let circuits = vec![w("huge", 5000)];
let b = budget(2000, 800, 100); let err = plan_incremental_deploy(&circuits, &b).unwrap_err();
assert!(format!("{err}").contains("huge"), "{err}");
assert!(format!("{err}").contains("raise --max-tx-bytes"), "{err}");
}
#[test]
fn errors_when_budget_below_maintenance_overhead() {
let circuits = vec![w("a", 10)];
let b = budget(100, 50, 100); let err = plan_incremental_deploy(&circuits, &b).unwrap_err();
assert!(
format!("{err}").contains("maintenance-tx overhead"),
"{err}"
);
}
#[test]
fn empty_contract_yields_lone_deploy() {
let plan = plan_incremental_deploy(&[], &budget(1000, 500, 100)).unwrap();
assert_eq!(plan.deploy_batch, [] as [CircuitId; 0]);
assert_eq!(plan.maintenance_batches, [] as [Vec<CircuitId>; 0]);
assert_eq!(plan.total_transactions(), 1);
assert!(plan.is_single_shot());
}
#[test]
fn plan_is_deterministic_for_equal_sizes() {
let circuits = vec![w("c", 100), w("a", 100), w("b", 100)];
let b = budget(1000, 950, 100);
let p1 = plan_incremental_deploy(&circuits, &b).unwrap();
let p2 = plan_incremental_deploy(&circuits, &b).unwrap();
assert_eq!(p1, p2);
}
fn writes(bytes_written: u64) -> CostVector {
CostVector {
bytes_written,
..CostVector::ZERO
}
}
fn costed(id: &str, deploy_writes: u64, maintenance_writes: u64) -> CircuitWeight {
CircuitWeight {
id: CircuitId::new(id),
vk_bytes: 100,
deploy_cost: writes(deploy_writes),
maintenance_cost: writes(maintenance_writes),
}
}
fn cost_budget(max_writes: u64, deploy_writes: u64, maintenance_writes: u64) -> PackBudget {
PackBudget {
max_tx_bytes: 1_000_000,
deploy_overhead: 0,
maintenance_overhead: 0,
max_cost: CostVector {
bytes_written: max_writes,
..CostVector::UNBOUNDED
},
deploy_overhead_cost: writes(deploy_writes),
maintenance_overhead_cost: writes(maintenance_writes),
}
}
#[test]
fn splits_by_cost_when_bytes_fit_one_transaction() {
let circuits: Vec<_> = (0..5)
.map(|i| costed(&format!("c{i}"), 3000, 3000))
.collect();
let plan = plan_incremental_deploy(&circuits, &cost_budget(7000, 1000, 500)).unwrap();
assert_eq!(plan.deploy_batch.len(), 2);
assert_eq!(
plan.maintenance_batches,
vec![
vec![CircuitId::new("c2"), CircuitId::new("c3")],
vec![CircuitId::new("c4")],
]
);
}
#[test]
fn errors_when_a_lone_circuit_exceeds_the_cost_limit() {
let circuits = vec![costed("heavy", 9000, 9000)];
let err = plan_incremental_deploy(&circuits, &cost_budget(7000, 1000, 500)).unwrap_err();
let message = format!("{err}");
assert!(message.contains("heavy"), "{message}");
assert!(message.contains("bytes written"), "{message}");
}
#[test]
fn errors_when_an_empty_deploy_exceeds_the_cost_limit() {
let err = plan_incremental_deploy(&[], &cost_budget(7000, 8000, 500)).unwrap_err();
assert!(format!("{err}").contains("empty deploy"), "{err}");
}
}