Skip to main content

moonproof_runtime/
trace.rs

1//! Structured execution tracing for the Compact runtime IR interpreter.
2//!
3//! Designed to be zero-cost when disabled (`TraceLevel::Off`): every hook in
4//! the interpreter checks `state.trace.is_some()` before constructing any
5//! event. When enabled (`Calls` or `Full`), captures the exact sequence of
6//! circuit frames, witness invocations, ledger ADT operations, emitted events,
7//! cross-contract hops, and assertion failures — including partial traces
8//! leading up to a revert.
9
10use std::fmt::Write as _;
11
12use moonproof_runtime_ir::RuntimeValue;
13use serde::{Deserialize, Serialize};
14
15/// Verbosity level controlling which interpreter events are recorded.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum TraceLevel {
19    /// Tracing disabled — zero allocation and zero overhead.
20    #[default]
21    Off,
22    /// Record circuit entries/exits, cross-contract hops, emitted events,
23    /// and assertion failures.
24    Calls,
25    /// Record everything in [`Self::Calls`] plus every witness invocation
26    /// (with arguments and observed return values) and every ledger ADT
27    /// operation (with VM op count and decoded read result).
28    Full,
29}
30
31impl TraceLevel {
32    /// Returns `true` when any tracing is enabled.
33    #[must_use]
34    pub const fn is_enabled(self) -> bool {
35        !matches!(self, Self::Off)
36    }
37
38    /// Returns `true` when witness invocations and ledger ADT operations
39    /// should be recorded in addition to call-frame events.
40    #[must_use]
41    pub const fn includes_details(self) -> bool {
42        matches!(self, Self::Full)
43    }
44
45    /// Parse a `MOONPROOF_TRACE` environment variable value.
46    #[must_use]
47    pub fn from_env_str(raw: &str) -> Self {
48        match raw.trim().to_ascii_lowercase().as_str() {
49            "1" | "2" | "true" | "yes" | "full" | "verbose" | "trace" => Self::Full,
50            "calls" | "summary" => Self::Calls,
51            _ => Self::Off,
52        }
53    }
54
55    /// Read the active trace level from the `MOONPROOF_TRACE` environment
56    /// variable, defaulting to [`Self::Off`].
57    #[must_use]
58    pub fn from_env() -> Self {
59        std::env::var("MOONPROOF_TRACE").map_or(Self::Off, |v| Self::from_env_str(&v))
60    }
61
62    /// Canonical string representation used for `MOONPROOF_TRACE`.
63    #[must_use]
64    pub const fn as_env_str(self) -> &'static str {
65        match self {
66            Self::Off => "off",
67            Self::Calls => "calls",
68            Self::Full => "full",
69        }
70    }
71}
72
73/// One structured event emitted by the runtime IR interpreter during circuit
74/// execution.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "snake_case")]
77pub enum TraceEvent {
78    /// Entered a circuit frame (root or cross-contract callee).
79    CircuitEnter {
80        contract: String,
81        circuit: String,
82        args: RuntimeValue,
83        depth: usize,
84    },
85    /// Exited a circuit frame normally with its return value.
86    CircuitExit {
87        contract: String,
88        circuit: String,
89        result: RuntimeValue,
90        depth: usize,
91    },
92    /// Invoked a host witness callback.
93    WitnessCall {
94        contract: String,
95        circuit: String,
96        witness: String,
97        args: RuntimeValue,
98        observed: RuntimeValue,
99        depth: usize,
100    },
101    /// Executed an on-chain ledger ADT operation (e.g. `Counter.increment`,
102    /// `Cell.write`, `Map.insert`).
103    LedgerOp {
104        contract: String,
105        adt: String,
106        operation: String,
107        vm_op_count: usize,
108        result: Option<RuntimeValue>,
109        depth: usize,
110    },
111    /// Emitted a contract event (`emit`).
112    EmitEvent {
113        contract: String,
114        version: u32,
115        tag: u32,
116        depth: usize,
117    },
118    /// Invoked a circuit on another deployed contract.
119    CrossContractCall {
120        caller: String,
121        callee: String,
122        circuit: String,
123        args: RuntimeValue,
124        depth: usize,
125    },
126    /// Failed an `assert(...)` inside a circuit.
127    AssertFailed {
128        contract: String,
129        circuit: String,
130        message: String,
131        depth: usize,
132    },
133}
134
135/// Ordered sequence of [`TraceEvent`]s recorded during a single circuit or
136/// call-tree execution.
137#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
138pub struct ExecutionTrace {
139    pub events: Vec<TraceEvent>,
140}
141
142impl ExecutionTrace {
143    /// Create an empty trace buffer.
144    #[must_use]
145    pub const fn new() -> Self {
146        Self { events: Vec::new() }
147    }
148
149    /// Returns `true` when no events have been recorded.
150    #[must_use]
151    pub fn is_empty(&self) -> bool {
152        self.events.is_empty()
153    }
154
155    /// Append one trace event.
156    pub fn push(&mut self, event: TraceEvent) {
157        self.events.push(event);
158    }
159
160    /// Clear all recorded events (used when a cross-contract call tree
161    /// retries after binding a newly discovered callee).
162    pub fn clear(&mut self) {
163        self.events.clear();
164    }
165
166    /// Iterate over every witness observation recorded in this trace as
167    /// `(contract, circuit, witness, observed_value)`.
168    pub fn witness_observations(&self) -> impl Iterator<Item = (&str, &str, &str, &RuntimeValue)> {
169        self.events.iter().filter_map(|ev| match ev {
170            TraceEvent::WitnessCall {
171                contract,
172                circuit,
173                witness,
174                observed,
175                ..
176            } => Some((
177                contract.as_str(),
178                circuit.as_str(),
179                witness.as_str(),
180                observed,
181            )),
182            _ => None,
183        })
184    }
185
186    /// Render the execution trace as an indented tree suitable for terminal
187    /// diagnostics.
188    #[must_use]
189    pub fn render(&self) -> String {
190        let mut out = String::new();
191        for ev in &self.events {
192            match ev {
193                TraceEvent::CircuitEnter {
194                    contract,
195                    circuit,
196                    args,
197                    depth,
198                } => {
199                    let prefix = indent(*depth);
200                    let _ = writeln!(
201                        out,
202                        "{prefix}{contract}.{circuit}({})",
203                        format_args_compact(args)
204                    );
205                }
206                TraceEvent::CircuitExit { result, depth, .. } => {
207                    let prefix = child_indent(*depth);
208                    let _ = writeln!(out, "{prefix}└─ return {}", format_value_compact(result));
209                }
210                TraceEvent::WitnessCall {
211                    witness,
212                    args,
213                    observed,
214                    depth,
215                    ..
216                } => {
217                    let prefix = child_indent(*depth);
218                    let _ = writeln!(
219                        out,
220                        "{prefix}├─ witness {witness}({}) => {}",
221                        format_args_compact(args),
222                        format_value_compact(observed)
223                    );
224                }
225                TraceEvent::LedgerOp {
226                    adt,
227                    operation,
228                    vm_op_count,
229                    result,
230                    depth,
231                    ..
232                } => {
233                    let prefix = child_indent(*depth);
234                    match result {
235                        Some(val) => {
236                            let _ = writeln!(
237                                out,
238                                "{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops) => {}",
239                                format_value_compact(val)
240                            );
241                        }
242                        None => {
243                            let _ = writeln!(
244                                out,
245                                "{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops)"
246                            );
247                        }
248                    }
249                }
250                TraceEvent::EmitEvent {
251                    version,
252                    tag,
253                    depth,
254                    ..
255                } => {
256                    let prefix = child_indent(*depth);
257                    let _ = writeln!(out, "{prefix}├─ emit event(v{version}, tag={tag})");
258                }
259                TraceEvent::CrossContractCall {
260                    callee,
261                    circuit,
262                    args,
263                    depth,
264                    ..
265                } => {
266                    let prefix = child_indent(*depth);
267                    let _ = writeln!(
268                        out,
269                        "{prefix}├─ call {callee}.{circuit}({})",
270                        format_args_compact(args)
271                    );
272                }
273                TraceEvent::AssertFailed { message, depth, .. } => {
274                    let prefix = child_indent(*depth);
275                    let _ = writeln!(out, "{prefix}└─ [REVERT] assert failed: {message:?}");
276                }
277            }
278        }
279        out
280    }
281}
282
283fn indent(depth: usize) -> String {
284    "│  ".repeat(depth)
285}
286
287fn child_indent(depth: usize) -> String {
288    format!("{}  ", "│  ".repeat(depth))
289}
290
291fn format_args_compact(args: &RuntimeValue) -> String {
292    match args {
293        RuntimeValue::Null => String::new(),
294        RuntimeValue::Array(items) if items.is_empty() => String::new(),
295        RuntimeValue::Array(items) => items
296            .iter()
297            .map(format_value_compact)
298            .collect::<Vec<_>>()
299            .join(", "),
300        other => format_value_compact(other),
301    }
302}
303
304/// Format a [`RuntimeValue`] concisely for trace display (truncating long
305/// byte arrays and deeply nested containers).
306#[must_use]
307pub fn format_value_compact(val: &RuntimeValue) -> String {
308    match val {
309        RuntimeValue::Null => "()".to_owned(),
310        RuntimeValue::Bool(b) => b.to_string(),
311        RuntimeValue::Int(n) => n.to_string(),
312        RuntimeValue::String(s) => {
313            if s.len() > 48 {
314                format!("\"{}…\" ({}B)", &s[..45], s.len())
315            } else {
316                format!("{s:?}")
317            }
318        }
319        RuntimeValue::Bytes(bytes) => {
320            if bytes.len() <= 8 {
321                format!("0x{}", hex::encode(bytes))
322            } else {
323                format!(
324                    "0x{}…{} ({}B)",
325                    hex::encode(&bytes[..4]),
326                    hex::encode(&bytes[bytes.len() - 2..]),
327                    bytes.len()
328                )
329            }
330        }
331        RuntimeValue::Array(items) => {
332            if items.is_empty() {
333                "[]".to_owned()
334            } else if items.len() <= 4 {
335                let inner = items
336                    .iter()
337                    .map(format_value_compact)
338                    .collect::<Vec<_>>()
339                    .join(", ");
340                format!("[{inner}]")
341            } else {
342                format!(
343                    "[{}, … ({} items)]",
344                    format_value_compact(&items[0]),
345                    items.len()
346                )
347            }
348        }
349        RuntimeValue::Object(map) => {
350            let mut parts = Vec::new();
351            for (i, (k, v)) in map.iter().enumerate() {
352                if i >= 4 {
353                    parts.push(format!("… ({} fields)", map.len()));
354                    break;
355                }
356                parts.push(format!("{k}: {}", format_value_compact(v)));
357            }
358            format!("{{{}}}", parts.join(", "))
359        }
360    }
361}
362
363/// Short hex label for a contract address when no human contract name is set.
364#[must_use]
365pub(crate) fn short_address(
366    addr: &moonproof_ledger::coin_structure::contract::ContractAddress,
367) -> String {
368    let hex_str = crate::state::contract_address_to_hex(addr);
369    if hex_str.len() > 10 {
370        format!("0x{}…{}", &hex_str[..6], &hex_str[hex_str.len() - 4..])
371    } else {
372        format!("0x{hex_str}")
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[test]
381    fn trace_level_env_parsing() {
382        assert_eq!(TraceLevel::from_env_str(""), TraceLevel::Off);
383        assert_eq!(TraceLevel::from_env_str("0"), TraceLevel::Off);
384        assert_eq!(TraceLevel::from_env_str("off"), TraceLevel::Off);
385        assert_eq!(TraceLevel::from_env_str("calls"), TraceLevel::Calls);
386        assert_eq!(TraceLevel::from_env_str("1"), TraceLevel::Full);
387        assert_eq!(TraceLevel::from_env_str("full"), TraceLevel::Full);
388        assert_eq!(TraceLevel::from_env_str("2"), TraceLevel::Full);
389    }
390
391    #[test]
392    fn render_nested_call_tree_and_revert() {
393        let mut trace = ExecutionTrace::new();
394        trace.push(TraceEvent::CircuitEnter {
395            contract: "vault".into(),
396            circuit: "withdraw".into(),
397            args: RuntimeValue::Int(100),
398            depth: 0,
399        });
400        trace.push(TraceEvent::WitnessCall {
401            contract: "vault".into(),
402            circuit: "withdraw".into(),
403            witness: "secret_key".into(),
404            args: RuntimeValue::Null,
405            observed: RuntimeValue::Bytes(vec![0xab; 32]),
406            depth: 0,
407        });
408        trace.push(TraceEvent::LedgerOp {
409            contract: "vault".into(),
410            adt: "Counter".into(),
411            operation: "increment".into(),
412            vm_op_count: 3,
413            result: None,
414            depth: 0,
415        });
416        trace.push(TraceEvent::AssertFailed {
417            contract: "vault".into(),
418            circuit: "withdraw".into(),
419            message: "insufficient balance".into(),
420            depth: 0,
421        });
422
423        let rendered = trace.render();
424        assert!(rendered.contains("vault.withdraw(100)"));
425        assert!(rendered.contains("witness secret_key() => 0xabababab…abab (32B)"));
426        assert!(rendered.contains("ledger Counter.increment (3 vm ops)"));
427        assert!(rendered.contains("[REVERT] assert failed: \"insufficient balance\""));
428        assert_eq!(trace.witness_observations().count(), 1);
429    }
430}