Skip to main content

moonproof_contracts/
incremental_deploy.rs

1//! Deploy a contract whose full verifier-key set is too large for one
2//! transaction, by splitting the work across several transactions.
3//!
4//! A transaction must fit the ledger's byte limit and, priced by the
5//! ledger's cost model against the current `LedgerParameters`, a share
6//! of the block limits: the node gives one normal transaction at most
7//! [`NORMAL_TRANSACTION_SHARE_PPM`] of each. A contract's deploy embeds
8//! one verifier key per circuit in its `ContractState.operations`
9//! table and writes all of them to state, so a contract with enough
10//! circuits — or large enough keys — produces a deploy the node
11//! refuses, long before its bytes approach the byte limit.
12//!
13//! The Contract Maintenance Authority makes the circuit set mutable
14//! after deploy: [`submit_insert_verifier_keys_tx`](crate::submit_insert_verifier_keys_tx)
15//! installs verifier keys for circuits that did not exist at deploy
16//! time. So a too-large contract can be deployed in passes:
17//!
18//! 1. **Deploy pass** — deploy the ledger state (the constructor runs
19//!    once, fixing the ledger schema) plus the subset of circuits whose
20//!    keys fit alongside it in one transaction
21//!    ([`DeployOptions::register_circuits`](crate::DeployOptions::register_circuits)).
22//! 2. **Maintenance passes** — install the remaining circuits, one
23//!    batch (one transaction) at a time, each batch sized to fit.
24//!
25//! This module owns the two halves of that: [`plan_deploy`] decides the
26//! batches (bin-packing against measured sizes and costs, each batch
27//! then checked against the ledger's cost model), and
28//! [`deploy_contract_incremental`] executes them.
29//!
30//! ## Constraints inherited from the maintenance mechanism
31//!
32//! - **The ledger schema is fixed at deploy.** Only the circuit set is
33//!   mutable afterwards. Every ledger field the contract will ever use
34//!   must be declared up front — splitting moves *circuits* across
35//!   transactions, never *state*.
36//! - **The maintenance authority key is the single point of control.**
37//!   The deploy installs it; every maintenance pass signs with it. Lose
38//!   it and the circuit set freezes permanently. The same key is reused
39//!   across all passes here — the deploy persists it under the contract
40//!   address and the maintenance passes read it back.
41
42use std::sync::Arc;
43use std::time::Duration;
44
45use moonproof_utils::rt::Instant;
46
47use moonproof_ledger::base_crypto::cost_model::{CostDuration, SyntheticCost};
48use moonproof_ledger::base_crypto::time::Timestamp;
49use moonproof_ledger::ledger::structure::{LedgerParameters, SingleUpdate};
50use moonproof_ledger::onchain_runtime::state::{
51    ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
52};
53use moonproof_ledger::storage::db::InMemoryDB;
54use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
55use rand::{CryptoRng, Rng};
56
57use moonproof_runtime::ir::witnesses::Witnesses;
58use moonproof_runtime::ir_executable::IrExecutable;
59
60use crate::contract::{deploy_contract, Contract};
61use crate::error::{ContractRuntimeError, Result};
62use crate::fee_balancing::FeeBalancingConfig;
63use crate::maintenance::{build_unproven_maintenance_tx, MaintenanceTxOptions};
64use crate::providers::{ErasedProviders, HasWallet, HasZkConfig, Providers, PublicDataProvider};
65use crate::submit_insert_vk_tx::{
66    submit_insert_verifier_keys_tx, SubmitInsertVerifierKeysTxOptions,
67};
68use crate::types::{CircuitId, FinalizedTxData};
69use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};
70
71mod plan;
72
73pub use plan::{plan_incremental_deploy, CircuitWeight, CostVector, DeployPlan, PackBudget};
74
75/// Default for the user's per-transaction byte cap: no cap beyond the
76/// ledger's and the node's own limits, which [`TransactionBudget`]
77/// always applies.
78pub const DEFAULT_MAX_TX_BYTES: usize = usize::MAX;
79
80/// The ledger's initial per-transaction byte limit
81/// (`INITIAL_LIMITS.transaction_byte_limit`). The limit in force is the
82/// current `LedgerParameters`', which [`TransactionBudget`] reads.
83pub const LEDGER_TX_BYTE_LIMIT: usize = 1 << 20;
84
85/// midnight-node's block weight: 2 s of reference time, in picoseconds
86/// (`runtime/src/lib.rs`, `BlockWeights`).
87const BLOCK_REF_TIME_PS: u64 = 2_000_000_000_000;
88
89/// The normal dispatch class's share of a block, in parts per million
90/// (`NORMAL_DISPATCH_RATIO`, 75%). Block length is capped the same way.
91const NORMAL_DISPATCH_PPM: u64 = 750_000;
92
93/// The share frame-system's `BlockWeights::with_sensible_defaults`
94/// reserves for block initialization out of every extrinsic's maximum
95/// (`avg_block_initialization(10%)`), in parts per million.
96const BLOCK_INITIALIZATION_PPM: u64 = 100_000;
97
98/// The weight the midnight pallet adds to every transaction
99/// (`EXTRA_WEIGHT_TX_SIZE`, 2·10¹⁰ ps, 1% of the block), in parts per
100/// million.
101const TRANSACTION_SIZE_WEIGHT_PPM: u64 = 10_000;
102
103/// frame-support's `ExtrinsicBaseWeight`, 108 157 ns, in picoseconds:
104/// subtracted from every normal extrinsic's maximum.
105const EXTRINSIC_BASE_WEIGHT_PS: u64 = 108_157_000;
106
107/// The share of each block limit one normal transaction may use, in
108/// parts per million. The node weighs a transaction as its largest
109/// normalized cost dimension times the block weight
110/// (`scale_normalized_cost`), plus the pallet's size weight, and
111/// frame-system refuses an extrinsic whose weight exceeds the normal
112/// class's maximum, 75% less the initialization reserve and the base
113/// extrinsic weight (`CheckWeight::check_extrinsic_weight`).
114pub const NORMAL_TRANSACTION_SHARE_PPM: u64 = NORMAL_DISPATCH_PPM
115    - BLOCK_INITIALIZATION_PPM
116    - TRANSACTION_SIZE_WEIGHT_PPM
117    - (EXTRINSIC_BASE_WEIGHT_PS * 1_000_000).div_ceil(BLOCK_REF_TIME_PS);
118
119/// The node's per-block length limit before the normal-class ratio
120/// (`BlockLength::max_with_normal_ratio(1024 * 1024, ..)`).
121const BLOCK_LENGTH_BYTES: u64 = 1024 * 1024;
122
123/// What the extrinsic adds around the transaction bytes: its compact
124/// length prefix (4), version byte (1), call index (2) and the
125/// transaction argument's compact length prefix (4).
126const EXTRINSIC_FRAMING_BYTES: u64 = 11;
127
128/// The largest transaction one normal extrinsic can carry under the
129/// node's block length limit.
130const NODE_TRANSACTION_BYTE_LIMIT: u64 =
131    BLOCK_LENGTH_BYTES * NORMAL_DISPATCH_PPM / 1_000_000 - EXTRINSIC_FRAMING_BYTES;
132
133/// A transaction's size and modelled cost.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct TxMeasure {
136    /// The larger of the serialized unproven transaction and the
137    /// ledger's estimate of the proven one.
138    pub bytes: usize,
139    /// The ledger's cost of the transaction, as the node prices it.
140    pub cost: SyntheticCost,
141}
142
143/// The limits one transaction must fit, from the current
144/// `LedgerParameters` and the node's share of a block.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct TransactionBudget {
147    pub max_bytes: usize,
148    pub max_cost: SyntheticCost,
149}
150
151impl TransactionBudget {
152    /// The budget under `params`, with an optional tighter byte cap.
153    #[must_use]
154    pub fn new(params: &LedgerParameters, max_tx_bytes: usize) -> Self {
155        let byte_limit = params
156            .limits
157            .transaction_byte_limit
158            .min(NODE_TRANSACTION_BYTE_LIMIT);
159        let block = params.limits.block_limits;
160        // `v * share / 10⁶`, split so the product cannot overflow.
161        let scale = |v: u64| {
162            v / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
163                + v % 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
164        };
165        let scale_time =
166            |d: CostDuration| CostDuration::from_picoseconds(scale(d.into_picoseconds()));
167        Self {
168            max_bytes: usize::try_from(byte_limit)
169                .unwrap_or(usize::MAX)
170                .min(max_tx_bytes),
171            max_cost: SyntheticCost {
172                read_time: scale_time(block.read_time),
173                compute_time: scale_time(block.compute_time),
174                block_usage: scale(block.block_usage),
175                bytes_written: scale(block.bytes_written),
176                bytes_churned: scale(block.bytes_churned),
177            },
178        }
179    }
180
181    /// Why `measure` does not fit, or `None` when it does.
182    #[must_use]
183    pub fn excess(&self, measure: &TxMeasure) -> Option<String> {
184        if measure.bytes > self.max_bytes {
185            return Some(format!(
186                "{} bytes, over the per-transaction limit of {}",
187                measure.bytes, self.max_bytes
188            ));
189        }
190        cost_vector(&measure.cost)
191            .first_excess(cost_vector(&self.max_cost))
192            .map(|(dimension, used, cap)| {
193                format!("{used} {dimension}, over the per-transaction limit of {cap}")
194            })
195    }
196}
197
198fn cost_vector(cost: &SyntheticCost) -> CostVector {
199    CostVector {
200        read_time_ps: cost.read_time.into_picoseconds(),
201        compute_time_ps: cost.compute_time.into_picoseconds(),
202        block_usage: cost.block_usage,
203        bytes_written: cost.bytes_written,
204        bytes_churned: cost.bytes_churned,
205    }
206}
207
208/// Measure an unproven transaction as the node will price it.
209///
210/// # Errors
211///
212/// When the transaction does not serialize, or the cost model refuses
213/// it outright (as the node would).
214pub fn measure_tx(
215    tx: &crate::tx_phase::UnprovenTx,
216    params: &LedgerParameters,
217) -> Result<TxMeasure> {
218    let serialized = tx
219        .to_tagged_bytes()
220        .map_err(|e| ContractRuntimeError::Provider {
221            provider: "measure_tx",
222            message: format!("serializing a sizing transaction: {e}"),
223        })?
224        .len();
225    let cost = tx
226        .as_inner()
227        .cost(params, true)
228        .map_err(|e| ContractRuntimeError::Provider {
229            provider: "measure_tx",
230            message: format!("the ledger's cost model refuses the transaction: {e:?}"),
231        })?;
232    Ok(TxMeasure {
233        bytes: serialized.max(usize::try_from(cost.block_usage).unwrap_or(usize::MAX)),
234        cost,
235    })
236}
237
238/// A circuit named in a plan, paired with its verifier key.
239///
240/// The orchestrator threads these from the zk-config provider into both
241/// the planner (which only reads the key length) and the executors
242/// (which install the key bytes).
243#[derive(Clone)]
244pub struct PlannedCircuit {
245    pub id: CircuitId,
246    pub vk: crate::types::VerifierKey,
247}
248
249/// Fresh dust fee-balancing inputs for one maintenance pass.
250pub struct PassFee {
251    pub fee_balancing: FeeBalancingConfig,
252    /// Chain-tip timestamp for this pass's intent TTL.
253    pub current_time: Timestamp,
254}
255
256/// Supplies fee-balancing inputs for each maintenance transaction.
257///
258/// Every pass spends dust, so the same `FeeBalancingConfig` cannot be
259/// reused across passes — its `DustState` would double-spend. The
260/// orchestrator calls [`PassFees::next_pass`] once before each
261/// maintenance transaction; the implementor (the CLI) re-syncs the
262/// wallet so each call returns unspent dust and a current chain tip.
263#[moonproof_macros::async_trait]
264pub trait PassFees: Send + Sync {
265    async fn next_pass(&self) -> Result<PassFee>;
266}
267
268/// Inputs to [`deploy_contract_incremental`].
269pub struct IncrementalDeployOptions<'a> {
270    /// The deploy transaction's options. `register_circuits` is
271    /// overwritten with the planner's deploy batch — set it to `None`.
272    /// `fee_balancing` / `current_time` here apply to the deploy
273    /// transaction only; maintenance passes get theirs from
274    /// [`IncrementalDeployOptions::pass_fees`].
275    pub deploy: DeployOptions,
276    /// Every provable circuit and its verifier key. Drives both the
277    /// plan (key sizes) and the maintenance inserts (key bytes).
278    pub circuits: Vec<PlannedCircuit>,
279    /// A byte cap tighter than the ledger's and the node's, which always
280    /// apply. [`DEFAULT_MAX_TX_BYTES`] sets none.
281    pub max_tx_bytes: usize,
282    /// The parameters of the current block: the limits every
283    /// transaction is planned against.
284    pub ledger_parameters: LedgerParameters,
285    /// Network id for the maintenance transactions (matches the
286    /// deploy's network).
287    pub network_id: String,
288    /// Fee source for maintenance passes.
289    pub pass_fees: &'a dyn PassFees,
290    /// How long to wait for the indexer to reflect a landed transaction
291    /// before the next pass (the maintenance counter must advance and
292    /// inserted circuits must be visible). Defaults to 60s via
293    /// [`IncrementalDeployOptions::new`].
294    pub sync_timeout: Duration,
295}
296
297impl<'a> IncrementalDeployOptions<'a> {
298    /// Build options with the default budget and a 60s indexer-sync
299    /// timeout.
300    #[must_use]
301    pub fn new(
302        deploy: DeployOptions,
303        circuits: Vec<PlannedCircuit>,
304        ledger_parameters: LedgerParameters,
305        network_id: String,
306        pass_fees: &'a dyn PassFees,
307    ) -> Self {
308        Self {
309            deploy,
310            circuits,
311            max_tx_bytes: DEFAULT_MAX_TX_BYTES,
312            ledger_parameters,
313            network_id,
314            pass_fees,
315            sync_timeout: Duration::from_mins(1),
316        }
317    }
318}
319
320/// Result of one maintenance pass.
321pub struct MaintenancePassResult {
322    pub circuits: Vec<CircuitId>,
323    pub tx: FinalizedTxData,
324}
325
326/// Outcome of an incremental deploy.
327pub struct IncrementalDeployOutcome<W: Witnesses + 'static> {
328    /// The deployed contract handle (from the deploy transaction).
329    pub contract: Contract<W>,
330    /// The plan that was executed.
331    pub plan: DeployPlan,
332    /// One entry per maintenance transaction, in order.
333    pub maintenance_passes: Vec<MaintenancePassResult>,
334}
335
336const SYNC_POLL_INTERVAL: Duration = Duration::from_secs(2);
337
338/// Deploy a contract across as many transactions as its verifier-key
339/// set requires.
340///
341/// Plans the split ([`plan_incremental_deploy`]) from each circuit's
342/// measured key size and the measured deploy / maintenance overheads,
343/// deploys the ledger plus the deploy batch in one transaction, then
344/// installs each remaining batch with a maintenance transaction —
345/// waiting for the indexer to reflect each pass before the next so the
346/// maintenance authority counter and circuit set are read fresh.
347///
348/// The deploy installs the maintenance authority signing key and
349/// persists it under the contract address; every maintenance pass signs
350/// with that same key (read back from the private-state provider).
351///
352/// # Errors
353///
354/// Propagates planning errors, the deploy error, any maintenance-pass
355/// submission error, and a timeout if the indexer does not reflect a
356/// landed pass within `sync_timeout`.
357pub async fn deploy_contract_incremental<W, R>(
358    rng: &mut R,
359    executable: Arc<IrExecutable<W>>,
360    providers: Arc<ErasedProviders>,
361    options: IncrementalDeployOptions<'_>,
362) -> Result<IncrementalDeployOutcome<W>>
363where
364    W: Witnesses + 'static,
365    R: Rng + CryptoRng,
366{
367    let IncrementalDeployOptions {
368        deploy: deploy_opts,
369        circuits,
370        max_tx_bytes,
371        ledger_parameters,
372        network_id,
373        pass_fees,
374        sync_timeout,
375    } = options;
376
377    let plan = plan_deploy(
378        rng,
379        executable.as_ref(),
380        providers.as_ref(),
381        &deploy_opts,
382        &circuits,
383        &TransactionBudget::new(&ledger_parameters, max_tx_bytes),
384        &ledger_parameters,
385    )
386    .await?;
387
388    // Index the verifier keys by circuit id for the maintenance passes.
389    let vk_of = |id: &CircuitId| {
390        circuits
391            .iter()
392            .find(|c| &c.id == id)
393            .map(|c| c.vk.clone())
394            .expect("planner only emits circuit ids drawn from `circuits`")
395    };
396
397    // (1) Deploy pass — ledger state + the deploy batch's verifier keys.
398    let mut deploy_opts = deploy_opts;
399    deploy_opts.register_circuits = Some(plan.deploy_batch.clone());
400    let contract = Box::pin(deploy_contract(
401        rng,
402        executable.clone(),
403        providers.clone(),
404        deploy_opts,
405    ))
406    .await?;
407    let address = *contract.contract_address();
408
409    // Wait for the indexer to surface the freshly-deployed contract
410    // before any maintenance query reads its (initially) empty state.
411    if !plan.maintenance_batches.is_empty() {
412        wait_for_contract_visible(providers.as_ref(), &address, sync_timeout).await?;
413    }
414
415    // (2) Maintenance passes — one transaction per remaining batch.
416    let mut maintenance_passes = Vec::with_capacity(plan.maintenance_batches.len());
417    for batch in &plan.maintenance_batches {
418        // Skip circuits already on-chain so a re-run (after an
419        // interruption or a partially-applied batch) is idempotent and
420        // never trips the "circuit already defined" guard.
421        let missing = filter_absent(providers.as_ref(), &address, batch).await?;
422        if missing.is_empty() {
423            continue;
424        }
425
426        let fee = pass_fees.next_pass().await?;
427        let batch_circuits: Vec<(CircuitId, crate::types::VerifierKey)> =
428            missing.iter().map(|id| (id.clone(), vk_of(id))).collect();
429
430        let tx = submit_insert_verifier_keys_tx(
431            rng,
432            providers.as_ref(),
433            SubmitInsertVerifierKeysTxOptions {
434                contract_address: address,
435                circuits: batch_circuits,
436                current_time: fee.current_time,
437                network_id: network_id.clone(),
438                fee_balancing: Some(fee.fee_balancing),
439            },
440        )
441        .await?;
442
443        // Gate the next pass on the indexer reflecting this one — the
444        // maintenance counter advances per applied update, and the next
445        // submit reads it fresh.
446        wait_for_circuits_present(providers.as_ref(), &address, &missing, sync_timeout).await?;
447
448        maintenance_passes.push(MaintenancePassResult {
449            circuits: missing,
450            tx,
451        });
452    }
453
454    Ok(IncrementalDeployOutcome {
455        contract,
456        plan,
457        maintenance_passes,
458    })
459}
460
461/// Plan an incremental deploy: measure each circuit's share of a deploy
462/// and of a maintenance transaction, pack the circuits under `budget`,
463/// then build every planned transaction and check it against `budget`
464/// as the ledger prices it, splitting any batch that does not fit.
465///
466/// The measured transactions carry the deploy's fee balancing, when
467/// `base` has it, so the dust spend each transaction gains at submit is
468/// inside the budget too.
469///
470/// Exposed so callers can preview the split — e.g. `moonproof deploy`
471/// uses it to report how many passes an `--incremental` deploy would
472/// take.
473///
474/// # Errors
475///
476/// Propagates measurement (tx-build) errors and
477/// [`plan_incremental_deploy`] errors; errors when even an empty deploy,
478/// or a lone circuit's maintenance transaction, exceeds the budget.
479pub async fn plan_deploy<W, C>(
480    rng: &mut (impl Rng + CryptoRng),
481    executable: &IrExecutable<W>,
482    providers: &C,
483    base: &DeployOptions,
484    circuits: &[PlannedCircuit],
485    budget: &TransactionBudget,
486    params: &LedgerParameters,
487) -> Result<DeployPlan>
488where
489    W: Witnesses + 'static,
490    C: HasWallet + HasZkConfig + ?Sized,
491{
492    let deploy_overhead =
493        measure_deploy_tx(rng, executable, providers, base, Some(Vec::new()), params).await?;
494    if let Some(excess) = budget.excess(&deploy_overhead) {
495        return Err(ContractRuntimeError::Provider {
496            provider: "plan_deploy",
497            message: format!("an empty deploy of this contract already needs {excess}"),
498        });
499    }
500    let fee = base.fee_balancing.as_ref();
501    let maintenance_overhead =
502        measure_maintenance_tx(rng, &[], &base.network_id, base.current_time, fee, params)?;
503
504    let mut weights = Vec::with_capacity(circuits.len());
505    for circuit in circuits {
506        let deploy = measure_deploy_tx(
507            rng,
508            executable,
509            providers,
510            base,
511            Some(vec![circuit.id.clone()]),
512            params,
513        )
514        .await?;
515        let maintenance = measure_maintenance_tx(
516            rng,
517            std::slice::from_ref(circuit),
518            &base.network_id,
519            base.current_time,
520            fee,
521            params,
522        )?;
523        weights.push(CircuitWeight {
524            id: circuit.id.clone(),
525            vk_bytes: circuit.vk.as_bytes().len(),
526            deploy_cost: cost_vector(&deploy.cost)
527                .saturating_sub(cost_vector(&deploy_overhead.cost)),
528            maintenance_cost: cost_vector(&maintenance.cost)
529                .saturating_sub(cost_vector(&maintenance_overhead.cost)),
530        });
531    }
532    let packed = plan_incremental_deploy(
533        &weights,
534        &PackBudget {
535            max_tx_bytes: budget.max_bytes,
536            deploy_overhead: deploy_overhead.bytes,
537            maintenance_overhead: maintenance_overhead.bytes,
538            max_cost: cost_vector(&budget.max_cost),
539            deploy_overhead_cost: cost_vector(&deploy_overhead.cost),
540            maintenance_overhead_cost: cost_vector(&maintenance_overhead.cost),
541        },
542    )?;
543
544    // The packing adds measured per-circuit costs; the ledger prices the
545    // whole transaction, so check each batch as built.
546    let (deploy_batch, spilled) = verify_deploy_batch(
547        rng,
548        executable,
549        providers,
550        base,
551        budget,
552        params,
553        packed.deploy_batch,
554    )
555    .await?;
556    let mut pending: std::collections::VecDeque<Vec<CircuitId>> = packed.maintenance_batches.into();
557    if !spilled.is_empty() {
558        pending.push_back(spilled);
559    }
560    Ok(DeployPlan {
561        deploy_batch,
562        maintenance_batches: verify_maintenance_batches(
563            rng, base, circuits, budget, params, pending,
564        )?,
565    })
566}
567
568/// Shrink the deploy batch, lightest circuit first, until the deploy
569/// fits `budget` as the ledger prices it. Returns the batch kept and the
570/// circuits moved out of it.
571async fn verify_deploy_batch<W, C>(
572    rng: &mut (impl Rng + CryptoRng),
573    executable: &IrExecutable<W>,
574    providers: &C,
575    base: &DeployOptions,
576    budget: &TransactionBudget,
577    params: &LedgerParameters,
578    mut batch: Vec<CircuitId>,
579) -> Result<(Vec<CircuitId>, Vec<CircuitId>)>
580where
581    W: Witnesses + 'static,
582    C: HasWallet + HasZkConfig + ?Sized,
583{
584    let mut spilled = Vec::new();
585    while !batch.is_empty() {
586        let measure = measure_deploy_tx(
587            rng,
588            executable,
589            providers,
590            base,
591            Some(batch.clone()),
592            params,
593        )
594        .await?;
595        if budget.excess(&measure).is_none() {
596            break;
597        }
598        spilled.extend(batch.pop());
599    }
600    Ok((batch, spilled))
601}
602
603/// Check each maintenance batch as built against `budget`, moving
604/// circuits out of one that does not fit into a batch of their own.
605fn verify_maintenance_batches(
606    rng: &mut (impl Rng + CryptoRng),
607    base: &DeployOptions,
608    circuits: &[PlannedCircuit],
609    budget: &TransactionBudget,
610    params: &LedgerParameters,
611    mut pending: std::collections::VecDeque<Vec<CircuitId>>,
612) -> Result<Vec<Vec<CircuitId>>> {
613    let by_id = |id: &CircuitId| {
614        circuits
615            .iter()
616            .find(|c| &c.id == id)
617            .cloned()
618            .ok_or_else(|| ContractRuntimeError::Provider {
619                provider: "plan_deploy",
620                message: format!("the plan names unknown circuit '{}'", id.as_str()),
621            })
622    };
623    let mut verified = Vec::new();
624    while let Some(mut batch) = pending.pop_front() {
625        let mut spilled = Vec::new();
626        loop {
627            let planned = batch.iter().map(&by_id).collect::<Result<Vec<_>>>()?;
628            let measure = measure_maintenance_tx(
629                rng,
630                &planned,
631                &base.network_id,
632                base.current_time,
633                base.fee_balancing.as_ref(),
634                params,
635            )?;
636            match budget.excess(&measure) {
637                None => break,
638                Some(excess) if batch.len() == 1 => {
639                    return Err(ContractRuntimeError::Provider {
640                        provider: "plan_deploy",
641                        message: format!(
642                            "circuit '{}' alone needs {excess} in a maintenance transaction; \
643                             this circuit cannot be deployed",
644                            batch[0].as_str()
645                        ),
646                    });
647                }
648                Some(_) => spilled.extend(batch.pop()),
649            }
650        }
651        verified.push(batch);
652        if !spilled.is_empty() {
653            pending.push_back(spilled);
654        }
655    }
656    Ok(verified)
657}
658
659/// Build a deploy transaction for `register_circuits` (all circuits when
660/// `None`) and measure it, with the fee balancing `base` carries.
661///
662/// With `Some(vec![])` this is the fixed deploy overhead (ledger state +
663/// authority + intent + framing). With `None` it is a single-shot
664/// deploy — what `moonproof deploy` checks against the
665/// [`TransactionBudget`] before attempting one.
666///
667/// # Errors
668///
669/// Propagates tx-build, serialization and cost-model errors.
670pub async fn measure_deploy_tx<W, C>(
671    rng: &mut (impl Rng + CryptoRng),
672    executable: &IrExecutable<W>,
673    providers: &C,
674    base: &DeployOptions,
675    register_circuits: Option<Vec<CircuitId>>,
676    params: &LedgerParameters,
677) -> Result<TxMeasure>
678where
679    W: Witnesses + 'static,
680    C: HasWallet + HasZkConfig + ?Sized,
681{
682    let sizing = DeployOptions {
683        constructor_args: base.constructor_args.clone(),
684        initial_private_state: base.initial_private_state.clone(),
685        signing_key: None,
686        additional_coin_enc_public_key_mappings: base
687            .additional_coin_enc_public_key_mappings
688            .clone(),
689        current_time: base.current_time,
690        network_id: base.network_id.clone(),
691        persistent_state: None,
692        fee_balancing: base.fee_balancing.clone(),
693        register_circuits,
694    };
695    let unproven = create_unproven_deploy_tx(rng, executable, providers, sizing).await?;
696    let tx =
697        unproven
698            .private
699            .unproven_tx
700            .as_ref()
701            .ok_or_else(|| ContractRuntimeError::Provider {
702                provider: "measure_deploy_tx",
703                message: "sizing deploy tx was not populated".to_owned(),
704            })?;
705    measure_tx(tx, params)
706}
707
708pub(crate) fn build_sizing_maintenance_tx(
709    rng: &mut (impl Rng + CryptoRng),
710    circuits: &[PlannedCircuit],
711    network_id: &str,
712    current_time: Timestamp,
713    fee_balancing: Option<&FeeBalancingConfig>,
714) -> Result<crate::tx_phase::UnprovenTx> {
715    // A throwaway authority whose committee accepts the signature — the
716    // transaction's serialized size is independent of which key signs.
717    let sizing_sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x01u8; 32])
718        .expect("32 bytes parse into a SigningKey");
719    let sizing_state = ContractState::<InMemoryDB>::new(
720        StateValue::Null,
721        StorageHashMap::new(),
722        ContractMaintenanceAuthority {
723            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
724                &sizing_sk,
725            )],
726            threshold: 1,
727            counter: 0,
728        },
729    );
730    let mut updates = Vec::with_capacity(circuits.len());
731    for circuit in circuits {
732        let entry: EntryPointBuf = circuit.id.as_str().as_bytes().into();
733        let ledger_vk: moonproof_ledger::transient_crypto::proofs::VerifierKey =
734            moonproof_ledger::serialize::tagged_deserialize(&mut circuit.vk.as_bytes()).map_err(
735                |e| ContractRuntimeError::Deserialize {
736                    context: "measure_maintenance_tx::tagged_deserialize(VerifierKey)",
737                    source: e,
738                },
739            )?;
740        updates.push(SingleUpdate::VerifierKeyInsert(
741            entry,
742            moonproof_ledger::versioned_verifier_key(ledger_vk),
743        ));
744    }
745    build_unproven_maintenance_tx(
746        rng,
747        MaintenanceTxOptions {
748            contract_address: moonproof_ledger::coin_structure::contract::ContractAddress(
749                moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
750            ),
751            on_chain_state: &sizing_state,
752            signing_key: &sizing_sk,
753            updates,
754            current_time,
755            network_id: network_id.to_owned(),
756            fee_balancing: fee_balancing.cloned(),
757        },
758    )
759}
760
761/// Build a maintenance transaction installing `circuits` against a
762/// synthetic state and measure it. The cost model prices a transaction
763/// from the transaction alone, so the state it would apply to does not
764/// change the measure.
765fn measure_maintenance_tx(
766    rng: &mut (impl Rng + CryptoRng),
767    circuits: &[PlannedCircuit],
768    network_id: &str,
769    current_time: Timestamp,
770    fee_balancing: Option<&FeeBalancingConfig>,
771    params: &LedgerParameters,
772) -> Result<TxMeasure> {
773    let unproven =
774        build_sizing_maintenance_tx(rng, circuits, network_id, current_time, fee_balancing)?;
775    measure_tx(&unproven, params)
776}
777
778/// Return the circuits in `batch` that are NOT yet present in the
779/// on-chain operations table. Used to make maintenance passes
780/// idempotent across re-runs.
781async fn filter_absent<C: Providers + ?Sized>(
782    providers: &C,
783    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
784    batch: &[CircuitId],
785) -> Result<Vec<CircuitId>> {
786    let state = providers
787        .public_data()
788        .query_contract_state(address, None)
789        .await?;
790    let Some(state) = state else {
791        // No state visible yet — treat everything as absent; the submit
792        // path will re-check and the pre-submit query will catch a truly
793        // missing contract.
794        return Ok(batch.to_vec());
795    };
796    Ok(batch
797        .iter()
798        .filter(|id| {
799            let entry: EntryPointBuf = id.as_str().as_bytes().into();
800            state.operations.get(&entry).is_none()
801        })
802        .cloned()
803        .collect())
804}
805
806/// Poll the indexer until a contract state is visible at `address`.
807async fn wait_for_contract_visible<C: Providers + ?Sized>(
808    providers: &C,
809    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
810    timeout: Duration,
811) -> Result<()> {
812    let start = Instant::now();
813    loop {
814        if providers
815            .public_data()
816            .query_contract_state(address, None)
817            .await?
818            .is_some()
819        {
820            return Ok(());
821        }
822        if start.elapsed() >= timeout {
823            return Err(ContractRuntimeError::Provider {
824                provider: "deploy_contract_incremental",
825                message: format!(
826                    "timed out after {:?} waiting for the indexer to surface deployed contract {}",
827                    timeout,
828                    moonproof_runtime::state::contract_address_to_hex(address),
829                ),
830            });
831        }
832        moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
833    }
834}
835
836/// Poll the indexer until every circuit in `batch` is present in the
837/// on-chain operations table — confirming the prior maintenance pass
838/// applied and the indexer caught up.
839async fn wait_for_circuits_present<C: Providers + ?Sized>(
840    providers: &C,
841    address: &moonproof_ledger::coin_structure::contract::ContractAddress,
842    batch: &[CircuitId],
843    timeout: Duration,
844) -> Result<()> {
845    let start = Instant::now();
846    loop {
847        if let Some(state) = providers
848            .public_data()
849            .query_contract_state(address, None)
850            .await?
851        {
852            let all_present = batch.iter().all(|id| {
853                let entry: EntryPointBuf = id.as_str().as_bytes().into();
854                state.operations.get(&entry).is_some()
855            });
856            if all_present {
857                return Ok(());
858            }
859        }
860        if start.elapsed() >= timeout {
861            return Err(ContractRuntimeError::Provider {
862                provider: "deploy_contract_incremental",
863                message: format!(
864                    "timed out after {:?} waiting for the indexer to reflect an inserted batch \
865                     ({} circuit(s)) on contract {}",
866                    timeout,
867                    batch.len(),
868                    moonproof_runtime::state::contract_address_to_hex(address),
869                ),
870            });
871        }
872        moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
873    }
874}
875
876#[cfg(test)]
877mod tests {
878    use super::*;
879    use crate::providers::{FileSystemZkConfigProvider, ZkConfigProvider};
880    use crate::test_helpers::scripted_providers;
881    use crate::types::TxStatus;
882    use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
883    use moonproof_runtime::NoWitnesses;
884    use moonproof_runtime_ir::RuntimeValue;
885    use rand::rngs::StdRng;
886    use rand::SeedableRng;
887
888    const FOREIGN_CURVES: &str = "extracted_foreign_curves_provable";
889
890    fn fixtures_dir() -> std::path::PathBuf {
891        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
892        p.pop();
893        p.push("runtime-ir/tests/fixtures");
894        p
895    }
896
897    /// The 13-circuit foreign-curves contract with compactc's verifier
898    /// keys, which only ledger 9 reads.
899    async fn foreign_curves() -> (IrExecutable<NoWitnesses>, Vec<PlannedCircuit>) {
900        let base = IrExecutable::from_path(
901            fixtures_dir().join(format!("{FOREIGN_CURVES}.cbor")),
902            Arc::new(NoWitnesses),
903        )
904        .unwrap();
905        let zk = FileSystemZkConfigProvider::new(fixtures_dir().join(FOREIGN_CURVES));
906        let mut planned = Vec::new();
907        let mut keys = std::collections::HashMap::new();
908        for id in base.provable_circuit_ids() {
909            let vk = zk.get_verifier_key(&id).await.unwrap();
910            keys.insert(id.as_str().to_owned(), vk.clone());
911            planned.push(PlannedCircuit { id, vk });
912        }
913        (base.with_verifier_keys(keys), planned)
914    }
915
916    fn deploy_options() -> DeployOptions {
917        DeployOptions {
918            constructor_args: RuntimeValue::Null,
919            initial_private_state: RuntimeValue::Null,
920            signing_key: None,
921            additional_coin_enc_public_key_mappings: None,
922            current_time: Timestamp::from_secs(1_700_000_000),
923            network_id: "local-test".to_owned(),
924            persistent_state: None,
925            fee_balancing: None,
926            register_circuits: None,
927        }
928    }
929
930    #[test]
931    fn a_normal_transaction_gets_the_node_share_of_each_block_limit() {
932        // 75% normal class, less 10% initialization, 1% size weight and
933        // the base extrinsic weight's 54.08 ppm, rounded up.
934        assert_eq!(NORMAL_TRANSACTION_SHARE_PPM, 639_945);
935        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
936        let block = INITIAL_PARAMETERS.limits.block_limits;
937        assert_eq!(
938            budget.max_cost.bytes_written,
939            block.bytes_written * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
940        );
941        assert_eq!(
942            budget.max_cost.compute_time.into_picoseconds(),
943            block.compute_time.into_picoseconds() / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
944        );
945        assert_eq!(budget.max_bytes, 786_421);
946    }
947
948    #[test]
949    fn a_byte_cap_tighter_than_the_limits_wins() {
950        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, 12_000);
951        assert_eq!(budget.max_bytes, 12_000);
952    }
953
954    #[test]
955    fn excess_names_the_dimension_over_its_limit() {
956        let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
957        let within = TxMeasure {
958            bytes: 1_000,
959            cost: SyntheticCost::ZERO,
960        };
961        assert_eq!(budget.excess(&within), None);
962        let writes_too_much = TxMeasure {
963            bytes: 1_000,
964            cost: SyntheticCost {
965                bytes_written: budget.max_cost.bytes_written + 1,
966                ..SyntheticCost::ZERO
967            },
968        };
969        let excess = budget.excess(&writes_too_much).unwrap();
970        assert!(excess.contains("bytes written"), "{excess}");
971        let too_large = TxMeasure {
972            bytes: budget.max_bytes + 1,
973            cost: SyntheticCost::ZERO,
974        };
975        assert!(budget.excess(&too_large).unwrap().contains("bytes"));
976    }
977
978    /// The foreign-curves deploy is far under the byte limit yet writes
979    /// more state than one transaction may: a plan by bytes alone ships
980    /// it in one transaction the node refuses. The plan by cost splits
981    /// it, and every transaction it plans fits as the ledger prices it.
982    #[tokio::test]
983    async fn the_foreign_curves_deploy_is_split_by_cost_not_bytes() {
984        if !moonproof_ledger::HAS_ZKIR_V3 {
985            return;
986        }
987        let (executable, planned) = foreign_curves().await;
988        assert_eq!(planned.len(), 13);
989        let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
990        let base = deploy_options();
991        let params = INITIAL_PARAMETERS;
992        let budget = TransactionBudget::new(&params, DEFAULT_MAX_TX_BYTES);
993        let mut rng = StdRng::seed_from_u64(0xF0_C0);
994
995        let single_shot =
996            measure_deploy_tx(&mut rng, &executable, &providers, &base, None, &params)
997                .await
998                .unwrap();
999        assert!(single_shot.bytes < budget.max_bytes, "{single_shot:?}");
1000        let excess = budget
1001            .excess(&single_shot)
1002            .expect("the single-shot deploy must exceed the cost limits");
1003        assert!(excess.contains("bytes written"), "{excess}");
1004
1005        let plan = plan_deploy(
1006            &mut rng,
1007            &executable,
1008            &providers,
1009            &base,
1010            &planned,
1011            &budget,
1012            &params,
1013        )
1014        .await
1015        .unwrap();
1016        assert!(!plan.is_single_shot(), "{plan:?}");
1017        assert_eq!(plan.total_circuits(), 13);
1018
1019        let deploy = measure_deploy_tx(
1020            &mut rng,
1021            &executable,
1022            &providers,
1023            &base,
1024            Some(plan.deploy_batch.clone()),
1025            &params,
1026        )
1027        .await
1028        .unwrap();
1029        assert_eq!(
1030            budget.excess(&deploy),
1031            None,
1032            "deploy batch {:?}",
1033            plan.deploy_batch
1034        );
1035        for batch in &plan.maintenance_batches {
1036            let circuits: Vec<PlannedCircuit> = batch
1037                .iter()
1038                .map(|id| planned.iter().find(|c| &c.id == id).unwrap().clone())
1039                .collect();
1040            let measure = measure_maintenance_tx(
1041                &mut rng,
1042                &circuits,
1043                &base.network_id,
1044                base.current_time,
1045                None,
1046                &params,
1047            )
1048            .unwrap();
1049            assert_eq!(budget.excess(&measure), None, "maintenance batch {batch:?}");
1050        }
1051    }
1052}