moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Pure bin-packing for an incremental deploy.
//!
//! Given each circuit's measured share of a deploy / maintenance
//! transaction — its bytes and its modelled cost — and the measured
//! fixed overhead of each transaction kind, decide which circuits ship
//! in the deploy and how the rest group into maintenance batches, so
//! every transaction stays within the per-transaction limits.
//!
//! Kept free of IO and ledger types so it can be exhaustively unit
//! tested with synthetic sizes; the orchestrator supplies the measured
//! weights and overheads, and checks each planned batch against the
//! ledger's own cost model before using it.

use crate::error::{ContractRuntimeError, Result};
use crate::types::CircuitId;

/// A transaction's modelled cost, one entry per dimension of the
/// ledger's `SyntheticCost`, durations in picoseconds.
#[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,
    };

    /// A capacity no cost reaches: packs by bytes alone.
    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),
        }
    }

    /// `true` when no dimension exceeds `capacity`'s.
    #[must_use]
    pub fn fits_within(self, capacity: Self) -> bool {
        self.first_excess(capacity).is_none()
    }

    /// The first dimension over `capacity`: its name, this value, and
    /// the capacity.
    #[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))
    }

    /// The largest share of `capacity` any dimension takes.
    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)
    }
}

/// `used / capacity`, compared exactly by cross-multiplying; a share of
/// no capacity is unbounded unless nothing is used.
#[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 {
        // Operands are at most `u64::MAX`, so the products fit in u128.
        (self.used * other.capacity).cmp(&(other.used * self.capacity))
    }
}

/// One circuit's contribution to a transaction: its verifier-key byte
/// length, which is what the operations table (deploy) or the
/// `VerifierKeyInsert` update (maintenance) actually carries, and the
/// cost it adds to each kind of transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CircuitWeight {
    pub id: CircuitId,
    pub vk_bytes: usize,
    /// The cost installing the key in the deploy adds.
    pub deploy_cost: CostVector,
    /// The cost installing the key in a maintenance transaction adds.
    pub maintenance_cost: CostVector,
}

/// The budget the planner packs against.
#[derive(Debug, Clone, Copy)]
pub struct PackBudget {
    /// Ceiling for any single transaction's projected size: the
    /// smallest of the user's `--max-tx-bytes` and the ledger's and the
    /// node's per-transaction byte limits.
    pub max_tx_bytes: usize,
    /// Measured fixed size of a deploy transaction carrying zero
    /// circuits — the ledger state, maintenance authority, intent, and
    /// serialization framing. The orchestrator obtains it by building an
    /// empty-subset deploy tx.
    pub deploy_overhead: usize,
    /// Measured fixed size of a maintenance transaction carrying zero
    /// verifier-key payload — the update framing, signature, and intent.
    pub maintenance_overhead: usize,
    /// The modelled cost any single transaction may reach.
    pub max_cost: CostVector,
    /// Measured cost of a deploy transaction carrying zero circuits.
    pub deploy_overhead_cost: CostVector,
    /// Measured cost of a maintenance transaction carrying zero updates.
    pub maintenance_overhead_cost: CostVector,
}

/// The decided batches. The deploy transaction always happens (it
/// creates the contract and its ledger state); `deploy_batch` is the
/// circuits installed alongside it and may be empty. Each entry of
/// `maintenance_batches` is one follow-up `VerifierKeyInsert`
/// transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeployPlan {
    pub deploy_batch: Vec<CircuitId>,
    pub maintenance_batches: Vec<Vec<CircuitId>>,
}

impl DeployPlan {
    /// Total circuits across deploy + maintenance.
    #[must_use]
    pub fn total_circuits(&self) -> usize {
        self.deploy_batch.len() + self.maintenance_batches.iter().map(Vec::len).sum::<usize>()
    }

    /// Total transactions: the deploy plus one per maintenance batch.
    #[must_use]
    pub fn total_transactions(&self) -> usize {
        1 + self.maintenance_batches.len()
    }

    /// `true` when the whole contract fits in the deploy transaction —
    /// no maintenance passes needed.
    #[must_use]
    pub fn is_single_shot(&self) -> bool {
        self.maintenance_batches.is_empty()
    }
}

/// A batch's running load: bytes and cost.
#[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)
    }
}

/// Pack circuits into a deploy batch + maintenance batches under the
/// budget, the heaviest first (first-fit-decreasing on each circuit's
/// dominant share of the per-transaction limits).
///
/// # Errors
///
/// - [`ContractRuntimeError::Provider`] if `max_tx_bytes` leaves no room
///   for even an empty maintenance transaction
///   (`max_tx_bytes <= maintenance_overhead`), if an empty deploy or
///   maintenance transaction already exceeds the cost limit, or if some
///   circuit's verifier key alone cannot fit any transaction at this
///   budget.
pub fn plan_incremental_deploy(
    circuits: &[CircuitWeight],
    budget: &PackBudget,
) -> Result<DeployPlan> {
    // Maintenance is the universal path — every circuit can be installed
    // by a maintenance tx, so its capacity gates feasibility. The deploy
    // batch is an optimization that piggybacks circuits onto the deploy
    // when its (larger) overhead leaves room.
    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)?;

    // First-fit-decreasing: heaviest first packs tightest.
    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()))
    });

    // Phase 1 — fill the single deploy batch.
    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);
        }
    }

    // Phase 2 — first-fit-decreasing the rest into maintenance bins.
    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(),
    })
}

/// Refuse a budget no plan can meet: an empty transaction already over
/// the cost limit, or a circuit too heavy for a maintenance transaction
/// of its own.
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}"
                ),
            });
        }
    }

    // Reject any circuit too large for the universal (maintenance) path.
    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,
        }
    }

    /// Helper: every batch's packed VK bytes stay within capacity.
    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() {
        // Each VK 1000 bytes. Deploy overhead 800, maintenance 100,
        // budget 2000 → deploy_cap 1200 (1 circuit), maint_cap 1900 (1
        // circuit per batch since 2 would be 2000 > 1900).
        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() {
        // 10 circuits of 100 bytes. Deploy overhead 950, maint 100,
        // budget 1000 → deploy_cap 50 (none fit), maint_cap 900 (9 per
        // batch). Expect deploy empty, 2 maintenance batches (9 + 1).
        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);
        // 9 fit per maintenance batch (900 cap / 100) → 2 batches.
        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)];
        // Deploy cap = 1500: big(1000)+mid(500) fit, small spills.
        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); // maint_cap 1900 < 5000
        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); // max_tx_bytes <= maintenance_overhead
        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() {
        // Each circuit writes 3000 bytes in either transaction; 7000 may
        // be written per transaction, 1000 already by the deploy.
        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}");
    }
}