Skip to main content

moonproof_runtime/
coverage.rs

1//! Zero-cost-when-disabled IR execution coverage collector.
2//!
3//! Indexes every circuit, conditional branch (`Statement::If` / `Expression::If`),
4//! assertion (`Expression::Assert`), ledger ADT operation (`Expression::AdtOp`),
5//! and contract event emission (`Expression::Emit`) inside a [`MoonIr`] into
6//! dense `u32` site tables keyed by the stable address of each IR node.
7//!
8//! Because `IrExecutable` owns its `MoonIr` inside an `Arc`, node addresses
9//! stay fixed for the executable's lifetime and require zero `unsafe` code
10//! (`std::ptr::from_ref(node) as usize`). When coverage is disabled, the
11//! interpreter holds `coverage: None` and skips all tracking with a single
12//! branch check.
13
14use std::sync::Arc;
15
16use moonproof_runtime_ir::ir::{CircuitBody, Expression, MoonIr, PathElement, Statement};
17use rustc_hash::FxHashMap;
18use serde::{Deserialize, Serialize};
19
20/// Whether a conditional branch came from a statement or expression `if`.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum BranchKind {
24    StmtIf,
25    ExprIf,
26}
27
28#[derive(Debug, Clone)]
29struct CircuitSite {
30    name: String,
31    internal_uniq: Option<u64>,
32    exported: bool,
33}
34
35#[derive(Debug, Clone)]
36struct BranchSite {
37    circuit_idx: u32,
38    kind: BranchKind,
39}
40
41#[derive(Debug, Clone)]
42struct AssertSite {
43    circuit_idx: u32,
44    message: String,
45}
46
47#[derive(Debug, Clone)]
48struct LedgerOpSite {
49    circuit_idx: u32,
50    field: Option<String>,
51    adt: String,
52    operation: String,
53}
54
55#[derive(Debug, Clone)]
56struct EmitSite {
57    circuit_idx: u32,
58    event_version: u32,
59    event_tag: u32,
60}
61
62/// Pre-indexed map of coverable IR sites for a single [`MoonIr`].
63///
64/// Built lazily the first time coverage is requested on an `IrExecutable`.
65#[derive(Debug, Clone)]
66pub struct IrCoverageMap {
67    circuits: Vec<CircuitSite>,
68    branches: Vec<BranchSite>,
69    asserts: Vec<AssertSite>,
70    ledger_ops: Vec<LedgerOpSite>,
71    emits: Vec<EmitSite>,
72    circuit_by_addr: FxHashMap<usize, u32>,
73    branch_by_addr: FxHashMap<usize, u32>,
74    assert_by_addr: FxHashMap<usize, u32>,
75    ledger_op_by_addr: FxHashMap<usize, u32>,
76    emit_by_addr: FxHashMap<usize, u32>,
77}
78
79impl IrCoverageMap {
80    /// Walk `ir` once in deterministic pre-order and assign dense site IDs.
81    #[must_use]
82    pub fn build(ir: &MoonIr) -> Self {
83        let mut map = Self {
84            circuits: Vec::with_capacity(ir.circuits.len()),
85            branches: Vec::new(),
86            asserts: Vec::new(),
87            ledger_ops: Vec::new(),
88            emits: Vec::new(),
89            circuit_by_addr: FxHashMap::default(),
90            branch_by_addr: FxHashMap::default(),
91            assert_by_addr: FxHashMap::default(),
92            ledger_op_by_addr: FxHashMap::default(),
93            emit_by_addr: FxHashMap::default(),
94        };
95        for circuit in &ir.circuits {
96            let Ok(circuit_idx) = u32::try_from(map.circuits.len()) else {
97                break;
98            };
99            map.circuit_by_addr
100                .insert(std::ptr::from_ref(circuit) as usize, circuit_idx);
101            map.circuits.push(CircuitSite {
102                name: circuit.name.clone(),
103                internal_uniq: circuit.internal_uniq,
104                exported: circuit.exported,
105            });
106            map.visit_statement(circuit_idx, &circuit.body);
107        }
108        map
109    }
110
111    /// Build a zeroed [`IrCoverageSnapshot`] describing all coverable sites in
112    /// the IR, used to seed coverage reports before any calls occur.
113    #[must_use]
114    pub fn empty_snapshot(&self) -> IrCoverageSnapshot {
115        self.build_snapshot(&[], &[], &[], &[], &[], &[], &[])
116    }
117
118    fn visit_statement(&mut self, circuit_idx: u32, stmt: &Statement) {
119        match stmt {
120            Statement::Seq { items } => {
121                for item in items {
122                    self.visit_statement(circuit_idx, item);
123                }
124            }
125            Statement::If { cond, then, r#else } => {
126                if let Ok(id) = u32::try_from(self.branches.len()) {
127                    self.branch_by_addr
128                        .insert(std::ptr::from_ref(stmt) as usize, id);
129                    self.branches.push(BranchSite {
130                        circuit_idx,
131                        kind: BranchKind::StmtIf,
132                    });
133                }
134                self.visit_expression(circuit_idx, cond);
135                self.visit_statement(circuit_idx, then);
136                if let Some(else_branch) = r#else {
137                    self.visit_statement(circuit_idx, else_branch);
138                }
139            }
140            Statement::Const { value, .. } | Statement::Expr { value } => {
141                self.visit_expression(circuit_idx, value);
142            }
143            Statement::ConstDestructure { .. } | Statement::Unimplemented | Statement::Noop => {}
144        }
145    }
146
147    fn visit_expression(&mut self, circuit_idx: u32, expr: &Expression) {
148        match expr {
149            Expression::If { cond, then, r#else } => {
150                self.register_branch(circuit_idx, expr, BranchKind::ExprIf);
151                self.visit_expression(circuit_idx, cond);
152                self.visit_expression(circuit_idx, then);
153                self.visit_expression(circuit_idx, r#else);
154            }
155            Expression::Assert { cond, message } => {
156                if let Ok(id) = u32::try_from(self.asserts.len()) {
157                    self.assert_by_addr
158                        .insert(std::ptr::from_ref(expr) as usize, id);
159                    self.asserts.push(AssertSite {
160                        circuit_idx,
161                        message: message.clone(),
162                    });
163                }
164                self.visit_expression(circuit_idx, cond);
165            }
166            Expression::AdtOp(inv) => {
167                if inv.adt != "Kernel" {
168                    if let Ok(id) = u32::try_from(self.ledger_ops.len()) {
169                        self.ledger_op_by_addr
170                            .insert(std::ptr::from_ref(expr) as usize, id);
171                        self.ledger_ops.push(LedgerOpSite {
172                            circuit_idx,
173                            field: inv.field.clone(),
174                            adt: inv.adt.clone(),
175                            operation: inv.operation.clone(),
176                        });
177                    }
178                }
179                for elem in &inv.field_path {
180                    if let PathElement::Expr { value, .. } = elem {
181                        self.visit_expression(circuit_idx, value);
182                    }
183                }
184                for arg in &inv.arguments {
185                    self.visit_expression(circuit_idx, arg);
186                }
187            }
188            Expression::Emit {
189                event_version,
190                event_tag,
191                payload,
192                ..
193            } => {
194                if let Ok(id) = u32::try_from(self.emits.len()) {
195                    self.emit_by_addr
196                        .insert(std::ptr::from_ref(expr) as usize, id);
197                    self.emits.push(EmitSite {
198                        circuit_idx,
199                        event_version: *event_version,
200                        event_tag: *event_tag,
201                    });
202                }
203                self.visit_expression(circuit_idx, payload);
204            }
205            other => self.visit_expression_children(circuit_idx, other),
206        }
207    }
208
209    fn register_branch<T>(&mut self, circuit_idx: u32, node: &T, kind: BranchKind) {
210        if let Ok(id) = u32::try_from(self.branches.len()) {
211            self.branch_by_addr
212                .insert(std::ptr::from_ref(node) as usize, id);
213            self.branches.push(BranchSite { circuit_idx, kind });
214        }
215    }
216
217    fn visit_expression_children(&mut self, circuit_idx: u32, expr: &Expression) {
218        match expr {
219            Expression::Tuple { items } | Expression::Vector { items } => {
220                for item in items {
221                    self.visit_expression(circuit_idx, &item.value);
222                }
223            }
224            Expression::Seq { items } => {
225                for item in items {
226                    self.visit_expression(circuit_idx, item);
227                }
228            }
229            Expression::Call { arguments, .. } | Expression::New { arguments, .. } => {
230                for arg in arguments {
231                    self.visit_expression(circuit_idx, arg);
232                }
233            }
234            Expression::ContractCall {
235                address, arguments, ..
236            } => {
237                self.visit_expression(circuit_idx, address);
238                for arg in arguments {
239                    self.visit_expression(circuit_idx, arg);
240                }
241            }
242            Expression::Binop { left, right, .. }
243            | Expression::Eq { left, right, .. }
244            | Expression::Neq { left, right, .. }
245            | Expression::And { left, right }
246            | Expression::Or { left, right } => {
247                self.visit_expression(circuit_idx, left);
248                self.visit_expression(circuit_idx, right);
249            }
250            Expression::VectorRef { value, index, .. }
251            | Expression::BytesRef { value, index, .. } => {
252                self.visit_expression(circuit_idx, value);
253                self.visit_expression(circuit_idx, index);
254            }
255            Expression::VectorSlice { value, start, .. }
256            | Expression::BytesSlice { value, start, .. } => {
257                self.visit_expression(circuit_idx, value);
258                self.visit_expression(circuit_idx, start);
259            }
260            Expression::EltRef { value, .. }
261            | Expression::TupleRef { value, .. }
262            | Expression::TupleSlice { value, .. }
263            | Expression::Not { value }
264            | Expression::Assign { value, .. }
265            | Expression::Cast { value, .. }
266            | Expression::SafeCast { value, .. }
267            | Expression::DowncastUnsigned { value, .. }
268            | Expression::FieldToBytes { value, .. }
269            | Expression::CastToField { value, .. }
270            | Expression::CastFromField { value, .. }
271            | Expression::CastFromBytes { value, .. }
272            | Expression::VectorToBytes { value, .. }
273            | Expression::BytesToVector { value, .. }
274            | Expression::CastFromEnum { value, .. }
275            | Expression::CastToEnum { value, .. } => {
276                self.visit_expression(circuit_idx, value);
277            }
278            Expression::If { .. }
279            | Expression::Assert { .. }
280            | Expression::AdtOp(_)
281            | Expression::Emit { .. }
282            | Expression::Literal { .. }
283            | Expression::Var { .. }
284            | Expression::Default { .. }
285            | Expression::EnumRef { .. }
286            | Expression::Map { .. }
287            | Expression::Fold { .. }
288            | Expression::Unimplemented => {}
289        }
290    }
291
292    #[allow(clippy::too_many_arguments)]
293    fn build_snapshot(
294        &self,
295        circuit_calls: &[u64],
296        branch_then: &[u64],
297        branch_else: &[u64],
298        assert_pass: &[u64],
299        assert_fail: &[u64],
300        ledger_op_hits: &[u64],
301        emit_hits: &[u64],
302    ) -> IrCoverageSnapshot {
303        let mut circuits: Vec<CircuitIrCoverage> = self
304            .circuits
305            .iter()
306            .enumerate()
307            .map(|(i, site)| CircuitIrCoverage {
308                name: site.name.clone(),
309                internal_uniq: site.internal_uniq,
310                exported: site.exported,
311                calls: circuit_calls.get(i).copied().unwrap_or(0),
312                branches: Vec::new(),
313                asserts: Vec::new(),
314                ledger_ops: Vec::new(),
315                emits: Vec::new(),
316            })
317            .collect();
318
319        for (i, site) in self.branches.iter().enumerate() {
320            if let Some(circuit) = circuits.get_mut(site.circuit_idx as usize) {
321                circuit.branches.push(BranchCoverage {
322                    kind: site.kind,
323                    then_hits: branch_then.get(i).copied().unwrap_or(0),
324                    else_hits: branch_else.get(i).copied().unwrap_or(0),
325                });
326            }
327        }
328        for (i, site) in self.asserts.iter().enumerate() {
329            if let Some(circuit) = circuits.get_mut(site.circuit_idx as usize) {
330                circuit.asserts.push(AssertCoverage {
331                    message: site.message.clone(),
332                    pass_hits: assert_pass.get(i).copied().unwrap_or(0),
333                    fail_hits: assert_fail.get(i).copied().unwrap_or(0),
334                });
335            }
336        }
337        for (i, site) in self.ledger_ops.iter().enumerate() {
338            if let Some(circuit) = circuits.get_mut(site.circuit_idx as usize) {
339                circuit.ledger_ops.push(LedgerOpCoverage {
340                    field: site.field.clone(),
341                    adt: site.adt.clone(),
342                    operation: site.operation.clone(),
343                    hits: ledger_op_hits.get(i).copied().unwrap_or(0),
344                });
345            }
346        }
347        for (i, site) in self.emits.iter().enumerate() {
348            if let Some(circuit) = circuits.get_mut(site.circuit_idx as usize) {
349                circuit.emits.push(EmitCoverage {
350                    event_version: site.event_version,
351                    event_tag: site.event_tag,
352                    hits: emit_hits.get(i).copied().unwrap_or(0),
353                });
354            }
355        }
356
357        IrCoverageSnapshot { circuits }
358    }
359}
360
361/// Live mutable hit counters accumulated during one or more circuit executions.
362#[derive(Debug, Clone)]
363pub struct IrCoverageCollector {
364    map: Arc<IrCoverageMap>,
365    circuit_calls: Vec<u64>,
366    branch_then: Vec<u64>,
367    branch_else: Vec<u64>,
368    assert_pass: Vec<u64>,
369    assert_fail: Vec<u64>,
370    ledger_op_hits: Vec<u64>,
371    emit_hits: Vec<u64>,
372}
373
374impl IrCoverageCollector {
375    /// Create a fresh zeroed collector bound to `map`.
376    #[must_use]
377    pub fn new(map: Arc<IrCoverageMap>) -> Self {
378        let circuit_calls = vec![0; map.circuits.len()];
379        let branch_then = vec![0; map.branches.len()];
380        let branch_else = vec![0; map.branches.len()];
381        let assert_pass = vec![0; map.asserts.len()];
382        let assert_fail = vec![0; map.asserts.len()];
383        let ledger_op_hits = vec![0; map.ledger_ops.len()];
384        let emit_hits = vec![0; map.emits.len()];
385        Self {
386            map,
387            circuit_calls,
388            branch_then,
389            branch_else,
390            assert_pass,
391            assert_fail,
392            ledger_op_hits,
393            emit_hits,
394        }
395    }
396
397    /// Reset all counters to zero (e.g. before replaying a call tree attempt).
398    pub fn clear(&mut self) {
399        self.circuit_calls.fill(0);
400        self.branch_then.fill(0);
401        self.branch_else.fill(0);
402        self.assert_pass.fill(0);
403        self.assert_fail.fill(0);
404        self.ledger_op_hits.fill(0);
405        self.emit_hits.fill(0);
406    }
407
408    /// Record entry into `circuit`.
409    pub fn record_circuit(&mut self, circuit: &CircuitBody) {
410        let addr = std::ptr::from_ref(circuit) as usize;
411        if let Some(&id) = self.map.circuit_by_addr.get(&addr) {
412            self.circuit_calls[id as usize] += 1;
413        }
414    }
415
416    /// Record a taken arm of `Statement::If`.
417    pub fn record_stmt_if(&mut self, stmt: &Statement, taken_then: bool) {
418        let addr = std::ptr::from_ref(stmt) as usize;
419        if let Some(&id) = self.map.branch_by_addr.get(&addr) {
420            if taken_then {
421                self.branch_then[id as usize] += 1;
422            } else {
423                self.branch_else[id as usize] += 1;
424            }
425        }
426    }
427
428    /// Record a taken arm of `Expression::If`.
429    pub fn record_expr_if(&mut self, expr: &Expression, taken_then: bool) {
430        let addr = std::ptr::from_ref(expr) as usize;
431        if let Some(&id) = self.map.branch_by_addr.get(&addr) {
432            if taken_then {
433                self.branch_then[id as usize] += 1;
434            } else {
435                self.branch_else[id as usize] += 1;
436            }
437        }
438    }
439
440    /// Record an `Expression::Assert` outcome (`passed == true` or reverted).
441    pub fn record_assert(&mut self, expr: &Expression, passed: bool) {
442        let addr = std::ptr::from_ref(expr) as usize;
443        if let Some(&id) = self.map.assert_by_addr.get(&addr) {
444            if passed {
445                self.assert_pass[id as usize] += 1;
446            } else {
447                self.assert_fail[id as usize] += 1;
448            }
449        }
450    }
451
452    /// Record execution of an `Expression::AdtOp` ledger operation.
453    pub fn record_adt_op(&mut self, expr: &Expression) {
454        let addr = std::ptr::from_ref(expr) as usize;
455        if let Some(&id) = self.map.ledger_op_by_addr.get(&addr) {
456            self.ledger_op_hits[id as usize] += 1;
457        }
458    }
459
460    /// Record execution of an `Expression::Emit` event emission.
461    pub fn record_emit(&mut self, expr: &Expression) {
462        let addr = std::ptr::from_ref(expr) as usize;
463        if let Some(&id) = self.map.emit_by_addr.get(&addr) {
464            self.emit_hits[id as usize] += 1;
465        }
466    }
467
468    /// Freeze the current counters into a serializable, mergeable snapshot.
469    #[must_use]
470    pub fn snapshot(&self) -> IrCoverageSnapshot {
471        self.map.build_snapshot(
472            &self.circuit_calls,
473            &self.branch_then,
474            &self.branch_else,
475            &self.assert_pass,
476            &self.assert_fail,
477            &self.ledger_op_hits,
478            &self.emit_hits,
479        )
480    }
481}
482
483/// Serializable deep IR coverage snapshot for one contract.
484#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
485pub struct IrCoverageSnapshot {
486    #[serde(default)]
487    pub circuits: Vec<CircuitIrCoverage>,
488}
489
490/// Deep IR coverage counters for a single circuit (exported or internal).
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
492pub struct CircuitIrCoverage {
493    pub name: String,
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub internal_uniq: Option<u64>,
496    pub exported: bool,
497    #[serde(default)]
498    pub calls: u64,
499    #[serde(default)]
500    pub branches: Vec<BranchCoverage>,
501    #[serde(default)]
502    pub asserts: Vec<AssertCoverage>,
503    #[serde(default)]
504    pub ledger_ops: Vec<LedgerOpCoverage>,
505    #[serde(default)]
506    pub emits: Vec<EmitCoverage>,
507}
508
509/// Hit counts for one conditional branch (`then` and `else`/fallthrough arms).
510#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
511pub struct BranchCoverage {
512    pub kind: BranchKind,
513    #[serde(default)]
514    pub then_hits: u64,
515    #[serde(default)]
516    pub else_hits: u64,
517}
518
519/// Hit counts for one `assert` site (both passing and reverting executions).
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
521pub struct AssertCoverage {
522    pub message: String,
523    #[serde(default)]
524    pub pass_hits: u64,
525    #[serde(default)]
526    pub fail_hits: u64,
527}
528
529/// Hit count for one ledger ADT operation site.
530#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
531pub struct LedgerOpCoverage {
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub field: Option<String>,
534    pub adt: String,
535    pub operation: String,
536    #[serde(default)]
537    pub hits: u64,
538}
539
540/// Hit count for one contract event `emit` site.
541#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
542pub struct EmitCoverage {
543    pub event_version: u32,
544    pub event_tag: u32,
545    #[serde(default)]
546    pub hits: u64,
547}
548
549/// Rolled-up numeric totals across one or more [`IrCoverageSnapshot`]s.
550#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
551pub struct IrCoverageTotals {
552    pub exported_circuits_hit: usize,
553    pub exported_circuits_total: usize,
554    pub internal_circuits_hit: usize,
555    pub internal_circuits_total: usize,
556    pub branch_arms_hit: usize,
557    pub branch_arms_total: usize,
558    pub asserts_passed: usize,
559    pub asserts_reverted: usize,
560    pub asserts_total: usize,
561    pub ledger_ops_hit: usize,
562    pub ledger_ops_total: usize,
563    pub emits_hit: usize,
564    pub emits_total: usize,
565}
566
567impl IrCoverageTotals {
568    /// Accumulate `other` into `self`.
569    pub fn add(&mut self, other: Self) {
570        self.exported_circuits_hit += other.exported_circuits_hit;
571        self.exported_circuits_total += other.exported_circuits_total;
572        self.internal_circuits_hit += other.internal_circuits_hit;
573        self.internal_circuits_total += other.internal_circuits_total;
574        self.branch_arms_hit += other.branch_arms_hit;
575        self.branch_arms_total += other.branch_arms_total;
576        self.asserts_passed += other.asserts_passed;
577        self.asserts_reverted += other.asserts_reverted;
578        self.asserts_total += other.asserts_total;
579        self.ledger_ops_hit += other.ledger_ops_hit;
580        self.ledger_ops_total += other.ledger_ops_total;
581        self.emits_hit += other.emits_hit;
582        self.emits_total += other.emits_total;
583    }
584}
585
586impl IrCoverageSnapshot {
587    /// Merge hit counts from `other` into `self` (used across multiple calls
588    /// and across parallel test processes).
589    pub fn merge(&mut self, other: &Self) {
590        for incoming in &other.circuits {
591            if let Some(existing) = self.circuits.iter_mut().find(|c| {
592                c.name == incoming.name
593                    && c.internal_uniq == incoming.internal_uniq
594                    && c.exported == incoming.exported
595            }) {
596                existing.calls += incoming.calls;
597                for (dst, src) in existing.branches.iter_mut().zip(&incoming.branches) {
598                    dst.then_hits += src.then_hits;
599                    dst.else_hits += src.else_hits;
600                }
601                for (dst, src) in existing.asserts.iter_mut().zip(&incoming.asserts) {
602                    dst.pass_hits += src.pass_hits;
603                    dst.fail_hits += src.fail_hits;
604                }
605                for (dst, src) in existing.ledger_ops.iter_mut().zip(&incoming.ledger_ops) {
606                    dst.hits += src.hits;
607                }
608                for (dst, src) in existing.emits.iter_mut().zip(&incoming.emits) {
609                    dst.hits += src.hits;
610                }
611            } else {
612                self.circuits.push(incoming.clone());
613            }
614        }
615    }
616
617    /// Compute rolled-up totals across all circuits in this snapshot.
618    #[must_use]
619    pub fn totals(&self) -> IrCoverageTotals {
620        let mut t = IrCoverageTotals::default();
621        for c in &self.circuits {
622            if c.exported {
623                t.exported_circuits_total += 1;
624                if c.calls > 0 {
625                    t.exported_circuits_hit += 1;
626                }
627            } else {
628                t.internal_circuits_total += 1;
629                if c.calls > 0 {
630                    t.internal_circuits_hit += 1;
631                }
632            }
633            for b in &c.branches {
634                t.branch_arms_total += 2;
635                if b.then_hits > 0 {
636                    t.branch_arms_hit += 1;
637                }
638                if b.else_hits > 0 {
639                    t.branch_arms_hit += 1;
640                }
641            }
642            for a in &c.asserts {
643                t.asserts_total += 1;
644                if a.pass_hits > 0 {
645                    t.asserts_passed += 1;
646                }
647                if a.fail_hits > 0 {
648                    t.asserts_reverted += 1;
649                }
650            }
651            for op in &c.ledger_ops {
652                t.ledger_ops_total += 1;
653                if op.hits > 0 {
654                    t.ledger_ops_hit += 1;
655                }
656            }
657            for ev in &c.emits {
658                t.emits_total += 1;
659                if ev.hits > 0 {
660                    t.emits_hit += 1;
661                }
662            }
663        }
664        t
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671    use moonproof_ledger::base_crypto::hash::HashOutput;
672    use moonproof_ledger::base_crypto::time::Timestamp;
673    use moonproof_ledger::coin_structure::contract::ContractAddress;
674    use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
675    use moonproof_runtime_ir::ir::{
676        Argument, CircuitBody, Constructor, Expression, MoonIr, StateValue, Statement,
677        TypeDescriptor,
678    };
679    use moonproof_runtime_ir::RuntimeValue;
680
681    use crate::{CircuitCallContext, ConstructorContext, IrExecutable, NoWitnesses, TraceLevel};
682
683    #[allow(clippy::default_trait_access)]
684    fn sample_ir() -> MoonIr {
685        MoonIr {
686            schema_version: 2,
687            compiler_version: "test".to_owned(),
688            language_version: "0.28".to_owned(),
689            runtime_version: "0.14".to_owned(),
690            contracts: Vec::new(),
691            ledger: Vec::new(),
692            witnesses: Vec::new(),
693            natives: Vec::new(),
694            circuits: vec![
695                CircuitBody {
696                    name: "check".to_owned(),
697                    internal_name: "check".to_owned(),
698                    internal_uniq: Some(1),
699                    exported: true,
700                    pure: false,
701                    proof: true,
702                    arguments: vec![Argument {
703                        name: "flag".to_owned(),
704                        arg_type: TypeDescriptor::Boolean,
705                    }],
706                    result_type: TypeDescriptor::Boolean,
707                    body: Statement::Seq {
708                        items: vec![
709                            Statement::Expr {
710                                value: Expression::Assert {
711                                    cond: Box::new(Expression::Var {
712                                        name: "flag".to_owned(),
713                                    }),
714                                    message: "flag must be true".to_owned(),
715                                },
716                            },
717                            Statement::If {
718                                cond: Expression::Var {
719                                    name: "flag".to_owned(),
720                                },
721                                then: Box::new(Statement::Expr {
722                                    value: Expression::Call {
723                                        function: "helper".to_owned(),
724                                        function_uniq: Some(2),
725                                        arguments: vec![Expression::Var {
726                                            name: "flag".to_owned(),
727                                        }],
728                                    },
729                                }),
730                                r#else: Some(Box::new(Statement::Expr {
731                                    value: Expression::Literal {
732                                        value: RuntimeValue::Bool(false),
733                                    },
734                                })),
735                            },
736                        ],
737                    },
738                },
739                CircuitBody {
740                    name: "helper".to_owned(),
741                    internal_name: "helper".to_owned(),
742                    internal_uniq: Some(2),
743                    exported: false,
744                    pure: true,
745                    proof: false,
746                    arguments: vec![Argument {
747                        name: "x".to_owned(),
748                        arg_type: TypeDescriptor::Boolean,
749                    }],
750                    result_type: TypeDescriptor::Boolean,
751                    body: Statement::Expr {
752                        value: Expression::If {
753                            cond: Box::new(Expression::Var {
754                                name: "x".to_owned(),
755                            }),
756                            then: Box::new(Expression::Literal {
757                                value: RuntimeValue::Bool(true),
758                            }),
759                            r#else: Box::new(Expression::Literal {
760                                value: RuntimeValue::Bool(false),
761                            }),
762                        },
763                    },
764                },
765            ],
766            descriptors: Default::default(),
767            constructor: Constructor {
768                arguments: Vec::new(),
769                initial_state: StateValue::Array { items: Vec::new() },
770                init_ops: Vec::new(),
771                register_operations: Vec::new(),
772                body: Statement::Noop,
773            },
774            external_contracts: Vec::new(),
775            pure_circuits: Vec::new(),
776            frontend: None,
777            debug_info: None,
778            capabilities: None,
779            workflows: Vec::new(),
780            privacy: None,
781            type_roles: Default::default(),
782        }
783    }
784
785    #[tokio::test]
786    async fn collector_tracks_branches_asserts_reverts_and_internal_helpers() {
787        let exec = IrExecutable::new(Arc::new(sample_ir()), Arc::new(NoWitnesses));
788        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x11u8; 32]).unwrap();
789        let coin_pk = crate::CoinPublicKey([0x22u8; 32]);
790        let init = exec
791            .initialize(
792                ConstructorContext {
793                    initial_private_state: RuntimeValue::Null,
794                    initial_zswap_local_state: crate::CompactZswapLocalState::empty(coin_pk),
795                    coin_public_key: coin_pk,
796                    signing_key,
797                    time: Some(Timestamp::from_secs(0)),
798                },
799                RuntimeValue::Null,
800            )
801            .await
802            .unwrap();
803
804        let make_ctx = || CircuitCallContext {
805            contract_address: ContractAddress(HashOutput([0x33u8; 32])),
806            contract_state: init.initial_contract_state.clone(),
807            private_state: RuntimeValue::Null,
808            ledger_parameters: INITIAL_PARAMETERS,
809            coin_public_key: coin_pk,
810            tblock: Timestamp::from_secs(0),
811        };
812
813        let mut cov_ok = IrCoverageCollector::new(exec.coverage_map());
814        exec.execute_circuit_instrumented(
815            "check",
816            make_ctx(),
817            RuntimeValue::Bool(true),
818            TraceLevel::Off,
819            None,
820            Some(&mut cov_ok),
821        )
822        .await
823        .expect("flag=true succeeds");
824
825        let mut cov_revert = IrCoverageCollector::new(exec.coverage_map());
826        let err = exec
827            .execute_circuit_instrumented(
828                "check",
829                make_ctx(),
830                RuntimeValue::Bool(false),
831                TraceLevel::Off,
832                None,
833                Some(&mut cov_revert),
834            )
835            .await
836            .expect_err("flag=false reverts");
837        assert!(matches!(
838            err,
839            crate::ContractRuntimeError::AssertionFailed(ref msg) if msg == "flag must be true"
840        ));
841
842        let mut merged = exec.coverage_map().empty_snapshot();
843        merged.merge(&cov_ok.snapshot());
844        merged.merge(&cov_revert.snapshot());
845
846        let totals = merged.totals();
847        assert_eq!(totals.exported_circuits_hit, 1);
848        assert_eq!(totals.exported_circuits_total, 1);
849        assert_eq!(totals.internal_circuits_hit, 1);
850        assert_eq!(totals.internal_circuits_total, 1);
851        // Two If sites (4 arms total); flag=true took `then` on both.
852        assert_eq!(totals.branch_arms_total, 4);
853        assert_eq!(totals.branch_arms_hit, 2);
854        // Single assert both passed AND reverted!
855        assert_eq!(totals.asserts_total, 1);
856        assert_eq!(totals.asserts_passed, 1);
857        assert_eq!(totals.asserts_reverted, 1);
858
859        let check = &merged.circuits[0];
860        assert_eq!(check.calls, 2);
861        assert_eq!(check.asserts[0].pass_hits, 1);
862        assert_eq!(check.asserts[0].fail_hits, 1);
863        assert_eq!(check.branches[0].then_hits, 1);
864        assert_eq!(check.branches[0].else_hits, 0);
865        let helper = &merged.circuits[1];
866        assert_eq!(helper.calls, 1);
867        assert_eq!(helper.branches[0].then_hits, 1);
868    }
869}