use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::structure::{LedgerParameters, INITIAL_PARAMETERS};
use moonproof_prover::{parse_zkir_json, parse_zkir_tagged, VersionedIr};
use moonproof_runtime::{IrExecutable, NoWitnesses};
use moonproof_runtime_ir::RuntimeValue;
use rand::rngs::StdRng;
use rand::SeedableRng;
use serde::{Deserialize, Serialize};
use crate::error::{ContractRuntimeError, Result};
use crate::incremental_deploy::{
build_sizing_maintenance_tx, measure_tx, plan_deploy, PlannedCircuit, TransactionBudget,
DEFAULT_MAX_TX_BYTES,
};
use crate::providers::{
FacadeWalletProvider, FileSystemZkConfigProvider, HasWallet, HasZkConfig, ZkConfigProvider,
};
use crate::types::CircuitId;
use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};
pub const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
pub const NEAR_CLIFF_THRESHOLD_BPS: u32 = 8_500;
pub const STANDARD_FEE_MARGIN_BLOCKS: usize = 5;
const SIZING_TIMESTAMP_SECS: u64 = 1_700_000_000;
const SIZING_RNG_SEED: u64 = 0x5A0A_5A0A_0011_0001;
#[must_use]
pub fn ledger_era_name() -> &'static str {
if moonproof_ledger::HAS_ZKIR_V3 {
"ledger9"
} else {
"ledger8"
}
}
mod u128_as_string {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(val: &u128, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&val.to_string())
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u128, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse::<u128>().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CircuitProfile {
pub name: String,
pub zkir_version: u8,
pub k: u8,
pub domain_size: u64,
pub rows: usize,
pub headroom_rows: u64,
pub utilization_bps: u32,
pub near_cliff: bool,
pub prover_key_bytes: u64,
pub verifier_key_bytes: u64,
pub bzkir_bytes: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub public_inputs: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub public_outputs: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instruction_count: Option<usize>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub opcode_histogram: BTreeMap<String, usize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CostDimension {
pub used: u64,
pub limit: u64,
pub pct_bps: u32,
}
impl CostDimension {
#[must_use]
pub fn new(used: u64, limit: u64) -> Self {
let pct_bps = if limit == 0 {
if used == 0 {
0
} else {
u32::MAX
}
} else {
let scaled = u128::from(used).saturating_mul(10_000) / u128::from(limit);
u32::try_from(scaled).unwrap_or(u32::MAX)
};
Self {
used,
limit,
pct_bps,
}
}
#[must_use]
pub fn exceeded(&self) -> bool {
self.used > self.limit
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeployProfile {
pub params_source: String,
pub single_shot_fits: bool,
pub total_transactions: usize,
pub maintenance_passes: usize,
pub tx_bytes: CostDimension,
pub read_time_ps: CostDimension,
pub compute_time_ps: CostDimension,
pub block_usage: CostDimension,
pub bytes_written: CostDimension,
pub bytes_churned: CostDimension,
pub bottleneck_dimension: String,
#[serde(with = "u128_as_string")]
pub estimated_dust_specks: u128,
#[serde(with = "u128_as_string")]
pub estimated_dust_with_margin_specks: u128,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub deploy_batch: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub maintenance_batches: Vec<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractProfile {
pub name: String,
pub circuits: BTreeMap<String, CircuitProfile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deploy: Option<DeployProfile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deploy_note: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotFile {
pub schema_version: u32,
pub ledger_era: String,
pub params_source: String,
pub contracts: BTreeMap<String, ContractProfile>,
}
impl SnapshotFile {
#[must_use]
pub fn new(params_source: impl Into<String>) -> Self {
Self {
schema_version: SNAPSHOT_SCHEMA_VERSION,
ledger_era: ledger_era_name().to_owned(),
params_source: params_source.into(),
contracts: BTreeMap::new(),
}
}
pub fn to_pretty_json(&self) -> std::result::Result<String, serde_json::Error> {
let mut s = serde_json::to_string_pretty(self)?;
s.push('\n');
Ok(s)
}
pub fn from_json(input: &str) -> std::result::Result<Self, serde_json::Error> {
serde_json::from_str(input)
}
}
#[derive(Clone)]
pub struct ProfileOptions {
pub params: LedgerParameters,
pub params_source: String,
pub max_tx_bytes: usize,
pub constructor_args: Option<RuntimeValue>,
pub network_id: String,
pub include_opcodes: bool,
}
impl Default for ProfileOptions {
fn default() -> Self {
Self {
params: INITIAL_PARAMETERS.clone(),
params_source: "initial-parameters".to_owned(),
max_tx_bytes: DEFAULT_MAX_TX_BYTES,
constructor_args: None,
network_id: "local-test".to_owned(),
include_opcodes: false,
}
}
}
struct OfflineSizingProviders {
wallet: FacadeWalletProvider,
zk_config: FileSystemZkConfigProvider,
}
impl OfflineSizingProviders {
fn new(contract_dir: &Path) -> Self {
Self {
wallet: FacadeWalletProvider::zero_keys(),
zk_config: FileSystemZkConfigProvider::new(contract_dir.to_path_buf()),
}
}
}
impl HasWallet for OfflineSizingProviders {
type Wallet = FacadeWalletProvider;
fn wallet(&self) -> &Self::Wallet {
&self.wallet
}
}
impl HasZkConfig for OfflineSizingProviders {
type ZkConfig = FileSystemZkConfigProvider;
fn zk_config(&self) -> &Self::ZkConfig {
&self.zk_config
}
}
#[derive(Deserialize)]
struct ZkirJsonSummary {
#[serde(default)]
inputs: Vec<serde_json::Value>,
#[serde(default)]
outputs: Vec<serde_json::Value>,
#[serde(default)]
instructions: Vec<ZkirJsonInstruction>,
}
#[derive(Deserialize)]
struct ZkirJsonInstruction {
op: String,
}
fn file_len_or_zero(path: &Path) -> u64 {
std::fs::metadata(path).map_or(0, |m| m.len())
}
fn load_versioned_ir(contract_dir: &Path, circuit_name: &str) -> Result<VersionedIr> {
let bzkir_path = contract_dir
.join("zkir")
.join(format!("{circuit_name}.bzkir"));
if bzkir_path.exists() {
let bytes = std::fs::read(&bzkir_path).map_err(|e| ContractRuntimeError::Provider {
provider: "profile_circuit",
message: format!("reading {}: {e}", bzkir_path.display()),
})?;
return parse_zkir_tagged(&bytes).map_err(|e| ContractRuntimeError::Provider {
provider: "profile_circuit",
message: format!("parsing {}: {e}", bzkir_path.display()),
});
}
let zkir_path = contract_dir
.join("zkir")
.join(format!("{circuit_name}.zkir"));
if zkir_path.exists() {
let json =
std::fs::read_to_string(&zkir_path).map_err(|e| ContractRuntimeError::Provider {
provider: "profile_circuit",
message: format!("reading {}: {e}", zkir_path.display()),
})?;
return parse_zkir_json(&json).map_err(|e| ContractRuntimeError::Provider {
provider: "profile_circuit",
message: format!("parsing {}: {e}", zkir_path.display()),
});
}
Err(ContractRuntimeError::Provider {
provider: "profile_circuit",
message: format!(
"neither zkir/{circuit_name}.bzkir nor zkir/{circuit_name}.zkir exists under {}",
contract_dir.display()
),
})
}
pub fn profile_circuit(
contract_dir: &Path,
circuit_name: &str,
include_opcodes: bool,
) -> Result<CircuitProfile> {
let ir = load_versioned_ir(contract_dir, circuit_name)?;
let zkir_version = ir.major();
let (k, rows) = ir.k_and_rows();
let domain_size = 1u64.checked_shl(u32::from(k)).unwrap_or(u64::MAX);
let rows_u64 = u64::try_from(rows).unwrap_or(u64::MAX);
let headroom_rows = domain_size.saturating_sub(rows_u64);
let utilization_bps = if domain_size == 0 {
10_000
} else {
let bps = u128::from(rows_u64).saturating_mul(10_000) / u128::from(domain_size);
u32::try_from(bps).unwrap_or(10_000).min(10_000)
};
let near_cliff = utilization_bps >= NEAR_CLIFF_THRESHOLD_BPS;
let keys_dir = contract_dir.join("keys");
let prover_key_bytes = file_len_or_zero(&keys_dir.join(format!("{circuit_name}.prover")));
let verifier_key_bytes = file_len_or_zero(&keys_dir.join(format!("{circuit_name}.verifier")));
let bzkir_bytes = file_len_or_zero(
&contract_dir
.join("zkir")
.join(format!("{circuit_name}.bzkir")),
);
let (public_inputs, public_outputs, instruction_count, opcode_histogram) =
parse_zkir_json_stats(
&contract_dir
.join("zkir")
.join(format!("{circuit_name}.zkir")),
include_opcodes,
);
Ok(CircuitProfile {
name: circuit_name.to_owned(),
zkir_version,
k,
domain_size,
rows,
headroom_rows,
utilization_bps,
near_cliff,
prover_key_bytes,
verifier_key_bytes,
bzkir_bytes,
public_inputs,
public_outputs,
instruction_count,
opcode_histogram,
})
}
fn parse_zkir_json_stats(
zkir_path: &Path,
include_opcodes: bool,
) -> (
Option<usize>,
Option<usize>,
Option<usize>,
BTreeMap<String, usize>,
) {
let Ok(raw) = std::fs::read_to_string(zkir_path) else {
return (None, None, None, BTreeMap::new());
};
let Ok(parsed) = serde_json::from_str::<ZkirJsonSummary>(&raw) else {
return (None, None, None, BTreeMap::new());
};
let mut histogram = BTreeMap::new();
if include_opcodes {
for instr in &parsed.instructions {
*histogram.entry(instr.op.clone()).or_insert(0) += 1;
}
}
(
Some(parsed.inputs.len()),
Some(parsed.outputs.len()),
Some(parsed.instructions.len()),
histogram,
)
}
fn locate_runtime_ir(contract_dir: &Path) -> Option<PathBuf> {
let nested = contract_dir.join("compiler").join("contract.mpir");
if nested.exists() {
return Some(nested);
}
let flat = contract_dir.join("contract.mpir");
if flat.exists() {
return Some(flat);
}
None
}
fn discover_zkir_circuit_names(contract_dir: &Path) -> BTreeSet<String> {
let mut names = BTreeSet::new();
let zkir_dir = contract_dir.join("zkir");
let Ok(entries) = std::fs::read_dir(&zkir_dir) else {
return names;
};
for entry in entries.flatten() {
let path = entry.path();
let ext = path.extension().and_then(|e| e.to_str());
if matches!(ext, Some("bzkir" | "zkir")) {
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
names.insert(stem.to_owned());
}
}
}
names
}
pub async fn profile_contract_dir(
name: &str,
contract_dir: &Path,
options: &ProfileOptions,
) -> Result<ContractProfile> {
if !contract_dir.exists() {
return Err(ContractRuntimeError::Provider {
provider: "profile_contract_dir",
message: format!(
"contract output directory does not exist: {}",
contract_dir.display()
),
});
}
let ir_path = locate_runtime_ir(contract_dir);
let executable = match &ir_path {
Some(path) => Some(
IrExecutable::from_path(path, Arc::new(NoWitnesses)).map_err(|e| {
ContractRuntimeError::Provider {
provider: "profile_contract_dir",
message: format!("loading {}: {e}", path.display()),
}
})?,
),
None => None,
};
let mut circuit_names = BTreeSet::new();
if let Some(exec) = &executable {
for id in exec.provable_circuit_ids() {
circuit_names.insert(id.as_str().to_owned());
}
}
if circuit_names.is_empty() {
circuit_names = discover_zkir_circuit_names(contract_dir);
}
let circuit_list: Vec<String> = circuit_names.into_iter().collect();
let circuits = profile_circuits_parallel(contract_dir, &circuit_list, options.include_opcodes)?;
let (deploy, deploy_note) = match executable {
None => (
None,
Some(
"contract.mpir not found; run `moonproof build` to enable deploy budget & DUST profiling"
.to_owned(),
),
),
Some(exec) => profile_deploy(contract_dir, exec, options).await?,
};
Ok(ContractProfile {
name: name.to_owned(),
circuits,
deploy,
deploy_note,
})
}
fn profile_circuits_parallel(
contract_dir: &Path,
circuit_names: &[String],
include_opcodes: bool,
) -> Result<BTreeMap<String, CircuitProfile>> {
if circuit_names.len() <= 1 {
let mut out = BTreeMap::new();
for cname in circuit_names {
let prof = profile_circuit(contract_dir, cname, include_opcodes)?;
out.insert(cname.clone(), prof);
}
return Ok(out);
}
let worker_count = std::thread::available_parallelism()
.map_or(4, std::num::NonZeroUsize::get)
.min(circuit_names.len());
let next_idx = std::sync::atomic::AtomicUsize::new(0);
let results: Vec<Result<Vec<(String, CircuitProfile)>>> = std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(worker_count);
for _ in 0..worker_count {
handles.push(scope.spawn(|| {
let mut local = Vec::new();
loop {
let i = next_idx.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let Some(cname) = circuit_names.get(i) else {
break;
};
let prof = profile_circuit(contract_dir, cname, include_opcodes)?;
local.push((cname.clone(), prof));
}
Ok(local)
}));
}
handles
.into_iter()
.map(|h| {
h.join().unwrap_or_else(|_| {
Err(ContractRuntimeError::Provider {
provider: "profile_contract_dir",
message: "circuit profiling worker thread panicked".to_owned(),
})
})
})
.collect()
});
let mut out = BTreeMap::new();
for worker_res in results {
for (cname, prof) in worker_res? {
out.insert(cname, prof);
}
}
Ok(out)
}
async fn load_planned_verifier_keys(
base_exec: &IrExecutable<NoWitnesses>,
providers: &OfflineSizingProviders,
) -> std::result::Result<
(
Vec<PlannedCircuit>,
HashMap<String, crate::types::VerifierKey>,
),
String,
> {
let circuit_ids = base_exec.provable_circuit_ids();
let mut planned = Vec::with_capacity(circuit_ids.len());
let mut vk_map = HashMap::with_capacity(circuit_ids.len());
for id in circuit_ids {
let vk = providers
.zk_config
.get_verifier_key(&id)
.await
.map_err(|e| {
format!(
"missing verifier key for `{}` ({e}); skipping deploy budget profiling",
id.as_str()
)
})?;
vk_map.insert(id.as_str().to_owned(), vk.clone());
planned.push(PlannedCircuit { id, vk });
}
Ok((planned, vk_map))
}
async fn profile_deploy(
contract_dir: &Path,
base_exec: IrExecutable<NoWitnesses>,
options: &ProfileOptions,
) -> Result<(Option<DeployProfile>, Option<String>)> {
let ctor_args_decl = &base_exec.ir().constructor.arguments;
let constructor_args = match (&options.constructor_args, ctor_args_decl.is_empty()) {
(Some(val), _) => val.clone(),
(None, true) => RuntimeValue::Null,
(None, false) => {
let names: Vec<&str> = ctor_args_decl.iter().map(|a| a.name.as_str()).collect();
return Ok((
None,
Some(format!(
"contract constructor requires argument(s) [{}]; configure \
[contracts.<name>.constructor_args] in moonproof.toml to profile deploy budget & DUST",
names.join(", ")
)),
));
}
};
let providers = OfflineSizingProviders::new(contract_dir);
let (planned, vk_map) = match load_planned_verifier_keys(&base_exec, &providers).await {
Ok(loaded) => loaded,
Err(note) => return Ok((None, Some(note))),
};
let executable = base_exec.with_verifier_keys(vk_map);
let deploy_opts = DeployOptions {
constructor_args,
initial_private_state: RuntimeValue::Null,
signing_key: None,
additional_coin_enc_public_key_mappings: None,
current_time: Timestamp::from_secs(SIZING_TIMESTAMP_SECS),
network_id: options.network_id.clone(),
persistent_state: None,
fee_balancing: None,
register_circuits: None,
};
let budget = TransactionBudget::new(&options.params, options.max_tx_bytes);
let mut rng = StdRng::seed_from_u64(SIZING_RNG_SEED);
let single_tx =
build_sizing_deploy_tx(&mut rng, &executable, &providers, &deploy_opts, None).await?;
let single_measure = measure_tx(&single_tx, &options.params)?;
let single_shot_fits = budget.excess(&single_measure).is_none();
let (
total_transactions,
maintenance_passes,
deploy_batch,
maintenance_batches,
estimated_dust_specks,
estimated_dust_with_margin_specks,
) = if single_shot_fits {
let fee0 = tx_fee(&single_tx, &options.params, 0)?;
let fee5 = tx_fee(&single_tx, &options.params, STANDARD_FEE_MARGIN_BLOCKS)?;
let batch = planned.iter().map(|c| c.id.as_str().to_owned()).collect();
(1, 0, batch, Vec::new(), fee0, fee5)
} else {
plan_and_price_incremental(
&mut rng,
&executable,
&providers,
&deploy_opts,
&planned,
&budget,
&options.params,
)
.await?
};
Ok((
Some(assemble_deploy_profile(
&options.params_source,
single_shot_fits,
total_transactions,
maintenance_passes,
&single_measure,
&budget,
estimated_dust_specks,
estimated_dust_with_margin_specks,
deploy_batch,
maintenance_batches,
)),
None,
))
}
#[allow(clippy::type_complexity)]
async fn plan_and_price_incremental<C: HasWallet + HasZkConfig + ?Sized>(
rng: &mut StdRng,
executable: &IrExecutable<NoWitnesses>,
providers: &C,
deploy_opts: &DeployOptions,
planned: &[PlannedCircuit],
budget: &TransactionBudget,
params: &LedgerParameters,
) -> Result<(usize, usize, Vec<String>, Vec<Vec<String>>, u128, u128)> {
let plan = plan_deploy(
rng,
executable,
providers,
deploy_opts,
planned,
budget,
params,
)
.await?;
let (fee0, fee5) = sum_incremental_fees(
rng,
executable,
providers,
deploy_opts,
planned,
&plan,
params,
)
.await?;
let d_batch = plan
.deploy_batch
.iter()
.map(|id| id.as_str().to_owned())
.collect();
let m_batches = plan
.maintenance_batches
.iter()
.map(|b| b.iter().map(|id| id.as_str().to_owned()).collect())
.collect();
Ok((
plan.total_transactions(),
plan.maintenance_batches.len(),
d_batch,
m_batches,
fee0,
fee5,
))
}
#[allow(clippy::too_many_arguments)]
fn assemble_deploy_profile(
params_source: &str,
single_shot_fits: bool,
total_transactions: usize,
maintenance_passes: usize,
single_measure: &crate::incremental_deploy::TxMeasure,
budget: &TransactionBudget,
estimated_dust_specks: u128,
estimated_dust_with_margin_specks: u128,
deploy_batch: Vec<String>,
maintenance_batches: Vec<Vec<String>>,
) -> DeployProfile {
let tx_bytes = CostDimension::new(
u64::try_from(single_measure.bytes).unwrap_or(u64::MAX),
u64::try_from(budget.max_bytes).unwrap_or(u64::MAX),
);
let read_time_ps = CostDimension::new(
single_measure.cost.read_time.into_picoseconds(),
budget.max_cost.read_time.into_picoseconds(),
);
let compute_time_ps = CostDimension::new(
single_measure.cost.compute_time.into_picoseconds(),
budget.max_cost.compute_time.into_picoseconds(),
);
let block_usage =
CostDimension::new(single_measure.cost.block_usage, budget.max_cost.block_usage);
let bytes_written = CostDimension::new(
single_measure.cost.bytes_written,
budget.max_cost.bytes_written,
);
let bytes_churned = CostDimension::new(
single_measure.cost.bytes_churned,
budget.max_cost.bytes_churned,
);
let bottleneck_dimension = [
("tx_bytes", tx_bytes.pct_bps),
("read_time", read_time_ps.pct_bps),
("compute_time", compute_time_ps.pct_bps),
("block_usage", block_usage.pct_bps),
("bytes_written", bytes_written.pct_bps),
("bytes_churned", bytes_churned.pct_bps),
]
.into_iter()
.max_by_key(|(_, pct)| *pct)
.map_or("tx_bytes", |(name, _)| name)
.to_owned();
DeployProfile {
params_source: params_source.to_owned(),
single_shot_fits,
total_transactions,
maintenance_passes,
tx_bytes,
read_time_ps,
compute_time_ps,
block_usage,
bytes_written,
bytes_churned,
bottleneck_dimension,
estimated_dust_specks,
estimated_dust_with_margin_specks,
deploy_batch,
maintenance_batches,
}
}
async fn build_sizing_deploy_tx<C: HasWallet + HasZkConfig + ?Sized>(
rng: &mut StdRng,
executable: &IrExecutable<NoWitnesses>,
providers: &C,
base: &DeployOptions,
register_circuits: Option<Vec<CircuitId>>,
) -> Result<crate::tx_phase::UnprovenTx> {
let sizing = DeployOptions {
constructor_args: base.constructor_args.clone(),
initial_private_state: base.initial_private_state.clone(),
signing_key: None,
additional_coin_enc_public_key_mappings: base
.additional_coin_enc_public_key_mappings
.clone(),
current_time: base.current_time,
network_id: base.network_id.clone(),
persistent_state: None,
fee_balancing: base.fee_balancing.clone(),
register_circuits,
};
let unproven = create_unproven_deploy_tx(rng, executable, providers, sizing).await?;
unproven
.private
.unproven_tx
.ok_or_else(|| ContractRuntimeError::Provider {
provider: "profile_deploy",
message: "sizing deploy transaction was not populated".to_owned(),
})
}
fn tx_fee(
tx: &crate::tx_phase::UnprovenTx,
params: &LedgerParameters,
margin_blocks: usize,
) -> Result<u128> {
tx.as_inner()
.fees_with_margin(params, margin_blocks)
.map_err(|e| ContractRuntimeError::Provider {
provider: "profile_deploy",
message: format!("ledger fee calculation failed (margin={margin_blocks}): {e:?}"),
})
}
async fn sum_incremental_fees<C: HasWallet + HasZkConfig + ?Sized>(
rng: &mut StdRng,
executable: &IrExecutable<NoWitnesses>,
providers: &C,
deploy_opts: &DeployOptions,
planned: &[PlannedCircuit],
plan: &crate::incremental_deploy::DeployPlan,
params: &LedgerParameters,
) -> Result<(u128, u128)> {
let deploy_tx = build_sizing_deploy_tx(
rng,
executable,
providers,
deploy_opts,
Some(plan.deploy_batch.clone()),
)
.await?;
let mut total_fee0 = tx_fee(&deploy_tx, params, 0)?;
let mut total_fee5 = tx_fee(&deploy_tx, params, STANDARD_FEE_MARGIN_BLOCKS)?;
for batch in &plan.maintenance_batches {
let circuits: Vec<PlannedCircuit> = batch
.iter()
.filter_map(|id| planned.iter().find(|c| &c.id == id).cloned())
.collect();
let maint_tx = build_sizing_maintenance_tx(
rng,
&circuits,
&deploy_opts.network_id,
deploy_opts.current_time,
deploy_opts.fee_balancing.as_ref(),
)?;
total_fee0 = total_fee0.saturating_add(tx_fee(&maint_tx, params, 0)?);
total_fee5 =
total_fee5.saturating_add(tx_fee(&maint_tx, params, STANDARD_FEE_MARGIN_BLOCKS)?);
}
Ok((total_fee0, total_fee5))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SnapshotPolicy {
pub max_row_growth_pct: Option<f64>,
pub max_dust_growth_pct: Option<f64>,
pub allow_k_increase: bool,
pub allow_pass_increase: bool,
}
impl Default for SnapshotPolicy {
fn default() -> Self {
Self {
max_row_growth_pct: Some(0.0),
max_dust_growth_pct: None,
allow_k_increase: false,
allow_pass_increase: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CircuitDiff {
pub circuit: String,
pub status: String,
pub baseline_k: Option<u8>,
pub current_k: Option<u8>,
pub k_delta: i16,
pub baseline_rows: Option<usize>,
pub current_rows: Option<usize>,
pub rows_delta: i64,
pub rows_pct_change: Option<f64>,
pub vk_bytes_delta: i64,
pub pk_bytes_delta: i64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeployDiff {
pub baseline_transactions: usize,
pub current_transactions: usize,
pub transactions_delta: i64,
pub tx_bytes_delta: i64,
pub bytes_written_delta: i64,
pub dust_delta_specks: i128,
pub dust_pct_change: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContractDiff {
pub contract: String,
pub circuits: Vec<CircuitDiff>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deploy: Option<DeployDiff>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Regression {
pub contract: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub circuit: Option<String>,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SnapshotDiff {
pub contracts: Vec<ContractDiff>,
pub regressions: Vec<Regression>,
}
impl SnapshotDiff {
#[must_use]
pub fn passed(&self) -> bool {
self.regressions.is_empty()
}
}
fn signed_delta_u64(before: u64, after: u64) -> i64 {
i64::try_from(i128::from(after) - i128::from(before)).unwrap_or(i64::MAX)
}
fn signed_delta_usize(before: usize, after: usize) -> i64 {
let b = i128::try_from(before).unwrap_or(i128::MAX);
let a = i128::try_from(after).unwrap_or(i128::MAX);
i64::try_from(a - b).unwrap_or(i64::MAX)
}
#[allow(clippy::cast_precision_loss)]
fn pct_change_u128(before: u128, after: u128) -> Option<f64> {
if before == 0 {
return None;
}
let delta = (after as f64) - (before as f64);
Some((delta / (before as f64)) * 100.0)
}
#[must_use]
pub fn diff_snapshots(
baseline: &SnapshotFile,
current: &SnapshotFile,
policy: &SnapshotPolicy,
) -> SnapshotDiff {
let mut all_contracts: BTreeSet<&str> = BTreeSet::new();
for k in baseline.contracts.keys() {
all_contracts.insert(k.as_str());
}
for k in current.contracts.keys() {
all_contracts.insert(k.as_str());
}
let mut contracts = Vec::new();
let mut regressions = Vec::new();
for cname in all_contracts {
let base_c = baseline.contracts.get(cname);
let curr_c = current.contracts.get(cname);
let circuit_diffs = diff_contract_circuits(cname, base_c, curr_c, policy, &mut regressions);
let deploy_diff = diff_contract_deploy(cname, base_c, curr_c, policy, &mut regressions);
contracts.push(ContractDiff {
contract: cname.to_owned(),
circuits: circuit_diffs,
deploy: deploy_diff,
});
}
SnapshotDiff {
contracts,
regressions,
}
}
fn diff_contract_circuits(
cname: &str,
base_c: Option<&ContractProfile>,
curr_c: Option<&ContractProfile>,
policy: &SnapshotPolicy,
regressions: &mut Vec<Regression>,
) -> Vec<CircuitDiff> {
let mut all_circuits: BTreeSet<&str> = BTreeSet::new();
if let Some(c) = base_c {
for k in c.circuits.keys() {
all_circuits.insert(k.as_str());
}
}
if let Some(c) = curr_c {
for k in c.circuits.keys() {
all_circuits.insert(k.as_str());
}
}
let mut out = Vec::new();
for circ in all_circuits {
let b = base_c.and_then(|c| c.circuits.get(circ));
let cur = curr_c.and_then(|c| c.circuits.get(circ));
match (b, cur) {
(Some(b), Some(cur)) => {
let k_delta = i16::from(cur.k) - i16::from(b.k);
let rows_delta = signed_delta_usize(b.rows, cur.rows);
let rows_pct = pct_change_u128(b.rows as u128, cur.rows as u128);
let vk_delta = signed_delta_u64(b.verifier_key_bytes, cur.verifier_key_bytes);
let pk_delta = signed_delta_u64(b.prover_key_bytes, cur.prover_key_bytes);
let status = if k_delta == 0 && rows_delta == 0 && vk_delta == 0 && pk_delta == 0 {
"unchanged"
} else {
"changed"
};
if !policy.allow_k_increase && k_delta > 0 {
regressions.push(Regression {
contract: cname.to_owned(),
circuit: Some(circ.to_owned()),
message: format!(
"Halo2 k increased from {} to {} (+{k_delta}, doubling proving domain)",
b.k, cur.k
),
});
}
if let (Some(max_pct), Some(pct)) = (policy.max_row_growth_pct, rows_pct) {
if rows_delta > 0 && pct > max_pct {
regressions.push(Regression {
contract: cname.to_owned(),
circuit: Some(circ.to_owned()),
message: format!(
"rows grew from {} to {} (+{rows_delta}, +{pct:.2}% > max {max_pct:.2}%)",
b.rows, cur.rows
),
});
}
}
out.push(CircuitDiff {
circuit: circ.to_owned(),
status: status.to_owned(),
baseline_k: Some(b.k),
current_k: Some(cur.k),
k_delta,
baseline_rows: Some(b.rows),
current_rows: Some(cur.rows),
rows_delta,
rows_pct_change: rows_pct,
vk_bytes_delta: vk_delta,
pk_bytes_delta: pk_delta,
});
}
(None, Some(cur)) => {
out.push(CircuitDiff {
circuit: circ.to_owned(),
status: "added".to_owned(),
baseline_k: None,
current_k: Some(cur.k),
k_delta: i16::from(cur.k),
baseline_rows: None,
current_rows: Some(cur.rows),
rows_delta: i64::try_from(cur.rows).unwrap_or(i64::MAX),
rows_pct_change: None,
vk_bytes_delta: i64::try_from(cur.verifier_key_bytes).unwrap_or(i64::MAX),
pk_bytes_delta: i64::try_from(cur.prover_key_bytes).unwrap_or(i64::MAX),
});
}
(Some(b), None) => {
out.push(CircuitDiff {
circuit: circ.to_owned(),
status: "removed".to_owned(),
baseline_k: Some(b.k),
current_k: None,
k_delta: -i16::from(b.k),
baseline_rows: Some(b.rows),
current_rows: None,
rows_delta: -i64::try_from(b.rows).unwrap_or(i64::MAX),
rows_pct_change: None,
vk_bytes_delta: -i64::try_from(b.verifier_key_bytes).unwrap_or(i64::MAX),
pk_bytes_delta: -i64::try_from(b.prover_key_bytes).unwrap_or(i64::MAX),
});
}
(None, None) => {}
}
}
out
}
fn diff_contract_deploy(
cname: &str,
base_c: Option<&ContractProfile>,
curr_c: Option<&ContractProfile>,
policy: &SnapshotPolicy,
regressions: &mut Vec<Regression>,
) -> Option<DeployDiff> {
let b = base_c.and_then(|c| c.deploy.as_ref())?;
let cur = curr_c.and_then(|c| c.deploy.as_ref())?;
let transactions_delta = signed_delta_usize(b.total_transactions, cur.total_transactions);
let tx_bytes_delta = signed_delta_u64(b.tx_bytes.used, cur.tx_bytes.used);
let bytes_written_delta = signed_delta_u64(b.bytes_written.used, cur.bytes_written.used);
let dust_delta = i128::try_from(cur.estimated_dust_specks).unwrap_or(i128::MAX)
- i128::try_from(b.estimated_dust_specks).unwrap_or(i128::MAX);
let dust_pct = pct_change_u128(b.estimated_dust_specks, cur.estimated_dust_specks);
if !policy.allow_pass_increase && transactions_delta > 0 {
regressions.push(Regression {
contract: cname.to_owned(),
circuit: None,
message: format!(
"deploy transaction count increased from {} to {} (+{transactions_delta})",
b.total_transactions, cur.total_transactions
),
});
}
if let (Some(max_pct), Some(pct)) = (policy.max_dust_growth_pct, dust_pct) {
if dust_delta > 0 && pct > max_pct {
regressions.push(Regression {
contract: cname.to_owned(),
circuit: None,
message: format!(
"deploy DUST fee grew from {} to {} Specks (+{pct:.2}% > max {max_pct:.2}%)",
b.estimated_dust_specks, cur.estimated_dust_specks
),
});
}
}
Some(DeployDiff {
baseline_transactions: b.total_transactions,
current_transactions: cur.total_transactions,
transactions_delta,
tx_bytes_delta,
bytes_written_delta,
dust_delta_specks: dust_delta,
dust_pct_change: dust_pct,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn test_fixtures_contracts_dir() -> PathBuf {
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.pop();
p.push("test-fixtures/contracts");
p
}
fn runtime_ir_fixtures_dir() -> PathBuf {
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.pop();
p.push("runtime-ir/tests/fixtures");
p
}
#[tokio::test]
async fn profiles_real_counter_fixture_with_opcodes_cost_and_dust() {
if !moonproof_ledger::HAS_ZKIR_V3 {
return;
}
let dir = test_fixtures_contracts_dir().join("counter");
let opts = ProfileOptions {
include_opcodes: true,
..ProfileOptions::default()
};
let profile = profile_contract_dir("counter", &dir, &opts).await.unwrap();
assert_eq!(profile.name, "counter");
assert!(profile.deploy_note.is_none());
let inc = profile
.circuits
.get("increment")
.expect("increment circuit");
assert_eq!(inc.zkir_version, 3);
assert!(inc.k >= 4 && inc.k <= 20, "unexpected k={}", inc.k);
assert_eq!(inc.domain_size, 1u64 << inc.k);
assert!(inc.rows > 0 && (inc.rows as u64) <= inc.domain_size);
assert_eq!(inc.headroom_rows, inc.domain_size - inc.rows as u64);
assert!(inc.prover_key_bytes > 0);
assert!(inc.verifier_key_bytes > 0);
assert!(inc.bzkir_bytes > 0);
assert_eq!(inc.instruction_count, Some(3));
assert_eq!(inc.opcode_histogram.get("impact"), Some(&3));
let deploy = profile.deploy.expect("deploy profile");
assert!(deploy.single_shot_fits);
assert_eq!(deploy.total_transactions, 1);
assert_eq!(deploy.maintenance_passes, 0);
assert!(deploy.tx_bytes.used > 0);
assert!(deploy.bytes_written.used > 0);
assert!(deploy.compute_time_ps.used > 0);
assert!(deploy.estimated_dust_specks > 0);
assert!(deploy.estimated_dust_with_margin_specks >= deploy.estimated_dust_specks);
}
#[tokio::test]
async fn profiles_vault_opcodes_and_detects_persistent_hash() {
if !moonproof_ledger::HAS_ZKIR_V3 {
return;
}
let dir = test_fixtures_contracts_dir().join("vault");
let opts = ProfileOptions {
include_opcodes: true,
..ProfileOptions::default()
};
let profile = profile_contract_dir("vault", &dir, &opts).await.unwrap();
let deposit = profile.circuits.get("deposit").expect("deposit circuit");
assert_eq!(deposit.public_inputs, Some(5));
assert_eq!(deposit.opcode_histogram.get("constrain_bits"), Some(&5));
assert_eq!(deposit.opcode_histogram.get("persistent_hash"), Some(&1));
assert_eq!(deposit.opcode_histogram.get("impact"), Some(&9));
}
#[tokio::test]
async fn detects_real_incremental_deploy_split_when_over_budget() {
if !moonproof_ledger::HAS_ZKIR_V3 {
return;
}
let fc_root = runtime_ir_fixtures_dir();
let fc_assets = fc_root.join("extracted_foreign_curves_provable");
let tmp = tempfile::tempdir().unwrap();
std::fs::copy(
fc_root.join("extracted_foreign_curves_provable.cbor"),
tmp.path().join("contract.mpir"),
)
.unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(fc_assets.join("compiler"), tmp.path().join("compiler"))
.unwrap();
std::os::unix::fs::symlink(fc_assets.join("keys"), tmp.path().join("keys")).unwrap();
std::os::unix::fs::symlink(fc_assets.join("zkir"), tmp.path().join("zkir")).unwrap();
}
#[cfg(unix)]
{
let profile =
profile_contract_dir("foreign_curves", tmp.path(), &ProfileOptions::default())
.await
.unwrap();
assert_eq!(profile.circuits.len(), 13);
let deploy = profile.deploy.unwrap_or_else(|| {
panic!("expected deploy profile, note: {:?}", profile.deploy_note)
});
assert!(!deploy.single_shot_fits);
assert!(deploy.total_transactions > 1);
assert_eq!(deploy.total_transactions, 1 + deploy.maintenance_passes);
assert_eq!(deploy.bottleneck_dimension, "bytes_written");
assert!(deploy.bytes_written.exceeded());
assert!(deploy.estimated_dust_specks > 0);
assert!(deploy.estimated_dust_with_margin_specks >= deploy.estimated_dust_specks);
}
let fc_no_ir =
profile_contract_dir("foreign_curves", &fc_assets, &ProfileOptions::default())
.await
.unwrap();
assert_eq!(fc_no_ir.circuits.len(), 13);
assert!(fc_no_ir.deploy.is_none());
assert!(fc_no_ir.deploy_note.is_some());
}
#[tokio::test]
async fn snapshot_json_is_deterministic_across_runs() {
if !moonproof_ledger::HAS_ZKIR_V3 {
return;
}
let dir = test_fixtures_contracts_dir().join("counter");
let opts = ProfileOptions::default();
let mut s1 = SnapshotFile::new(&opts.params_source);
s1.contracts.insert(
"counter".to_owned(),
profile_contract_dir("counter", &dir, &opts).await.unwrap(),
);
let mut s2 = SnapshotFile::new(&opts.params_source);
s2.contracts.insert(
"counter".to_owned(),
profile_contract_dir("counter", &dir, &opts).await.unwrap(),
);
let j1 = s1.to_pretty_json().unwrap();
let j2 = s2.to_pretty_json().unwrap();
assert_eq!(j1, j2);
let roundtrip = SnapshotFile::from_json(&j1).unwrap();
assert_eq!(roundtrip, s1);
}
#[test]
fn diff_snapshots_enforces_k_rows_passes_and_dust_policy() {
let mut base = SnapshotFile::new("initial-parameters");
let mut circuits = BTreeMap::new();
circuits.insert(
"mint".to_owned(),
CircuitProfile {
name: "mint".to_owned(),
zkir_version: 3,
k: 12,
domain_size: 4096,
rows: 3000,
headroom_rows: 1096,
utilization_bps: 7324,
near_cliff: false,
prover_key_bytes: 100_000,
verifier_key_bytes: 2_000,
bzkir_bytes: 500,
public_inputs: None,
public_outputs: None,
instruction_count: None,
opcode_histogram: BTreeMap::new(),
},
);
base.contracts.insert(
"token".to_owned(),
ContractProfile {
name: "token".to_owned(),
circuits,
deploy: Some(DeployProfile {
params_source: "initial-parameters".to_owned(),
single_shot_fits: true,
total_transactions: 1,
maintenance_passes: 0,
tx_bytes: CostDimension::new(5000, 786_421),
read_time_ps: CostDimension::new(100, 1000),
compute_time_ps: CostDimension::new(100, 1000),
block_usage: CostDimension::new(5000, 100_000),
bytes_written: CostDimension::new(2000, 37_260),
bytes_churned: CostDimension::new(0, 100_000),
bottleneck_dimension: "bytes_written".to_owned(),
estimated_dust_specks: 1_000_000,
estimated_dust_with_margin_specks: 1_200_000,
deploy_batch: vec!["mint".to_owned()],
maintenance_batches: Vec::new(),
}),
deploy_note: None,
},
);
let strict = SnapshotPolicy::default();
assert!(diff_snapshots(&base, &base, &strict).passed());
let mut improved = base.clone();
improved
.contracts
.get_mut("token")
.unwrap()
.circuits
.get_mut("mint")
.unwrap()
.rows = 2800;
improved
.contracts
.get_mut("token")
.unwrap()
.deploy
.as_mut()
.unwrap()
.estimated_dust_specks = 900_000;
assert!(diff_snapshots(&base, &improved, &strict).passed());
let mut regressed = base.clone();
let mc = regressed
.contracts
.get_mut("token")
.unwrap()
.circuits
.get_mut("mint")
.unwrap();
mc.k = 13;
mc.domain_size = 8192;
mc.rows = 3300;
let dep = regressed
.contracts
.get_mut("token")
.unwrap()
.deploy
.as_mut()
.unwrap();
dep.single_shot_fits = false;
dep.total_transactions = 2;
dep.maintenance_passes = 1;
dep.estimated_dust_specks = 1_200_000;
let policy = SnapshotPolicy {
max_row_growth_pct: Some(5.0),
max_dust_growth_pct: Some(10.0),
allow_k_increase: false,
allow_pass_increase: false,
};
let diff = diff_snapshots(&base, ®ressed, &policy);
assert!(!diff.passed());
assert_eq!(diff.regressions.len(), 4, "{:?}", diff.regressions);
}
}