moonproof-runtime 0.2.2

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
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
//! Structured execution tracing for the Compact runtime IR interpreter.
//!
//! Designed to be zero-cost when disabled (`TraceLevel::Off`): every hook in
//! the interpreter checks `state.trace.is_some()` before constructing any
//! event. When enabled (`Calls` or `Full`), captures the exact sequence of
//! circuit frames, witness invocations, ledger ADT operations, emitted events,
//! cross-contract hops, and assertion failures — including partial traces
//! leading up to a revert.

use std::fmt::Write as _;

use moonproof_runtime_ir::RuntimeValue;
use serde::{Deserialize, Serialize};

/// Verbosity level controlling which interpreter events are recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TraceLevel {
    /// Tracing disabled — zero allocation and zero overhead.
    #[default]
    Off,
    /// Record circuit entries/exits, cross-contract hops, emitted events,
    /// and assertion failures.
    Calls,
    /// Record everything in [`Self::Calls`] plus every witness invocation
    /// (with arguments and observed return values) and every ledger ADT
    /// operation (with VM op count and decoded read result).
    Full,
}

impl TraceLevel {
    /// Returns `true` when any tracing is enabled.
    #[must_use]
    pub const fn is_enabled(self) -> bool {
        !matches!(self, Self::Off)
    }

    /// Returns `true` when witness invocations and ledger ADT operations
    /// should be recorded in addition to call-frame events.
    #[must_use]
    pub const fn includes_details(self) -> bool {
        matches!(self, Self::Full)
    }

    /// Parse a `MOONPROOF_TRACE` environment variable value.
    #[must_use]
    pub fn from_env_str(raw: &str) -> Self {
        match raw.trim().to_ascii_lowercase().as_str() {
            "1" | "2" | "true" | "yes" | "full" | "verbose" | "trace" => Self::Full,
            "calls" | "summary" => Self::Calls,
            _ => Self::Off,
        }
    }

    /// Read the active trace level from the `MOONPROOF_TRACE` environment
    /// variable, defaulting to [`Self::Off`].
    #[must_use]
    pub fn from_env() -> Self {
        std::env::var("MOONPROOF_TRACE").map_or(Self::Off, |v| Self::from_env_str(&v))
    }

    /// Canonical string representation used for `MOONPROOF_TRACE`.
    #[must_use]
    pub const fn as_env_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Calls => "calls",
            Self::Full => "full",
        }
    }
}

/// One structured event emitted by the runtime IR interpreter during circuit
/// execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TraceEvent {
    /// Entered a circuit frame (root or cross-contract callee).
    CircuitEnter {
        contract: String,
        circuit: String,
        args: RuntimeValue,
        depth: usize,
    },
    /// Exited a circuit frame normally with its return value.
    CircuitExit {
        contract: String,
        circuit: String,
        result: RuntimeValue,
        depth: usize,
    },
    /// Invoked a host witness callback.
    WitnessCall {
        contract: String,
        circuit: String,
        witness: String,
        args: RuntimeValue,
        observed: RuntimeValue,
        depth: usize,
    },
    /// Executed an on-chain ledger ADT operation (e.g. `Counter.increment`,
    /// `Cell.write`, `Map.insert`).
    LedgerOp {
        contract: String,
        adt: String,
        operation: String,
        vm_op_count: usize,
        result: Option<RuntimeValue>,
        depth: usize,
    },
    /// Emitted a contract event (`emit`).
    EmitEvent {
        contract: String,
        version: u32,
        tag: u32,
        depth: usize,
    },
    /// Invoked a circuit on another deployed contract.
    CrossContractCall {
        caller: String,
        callee: String,
        circuit: String,
        args: RuntimeValue,
        depth: usize,
    },
    /// Failed an `assert(...)` inside a circuit.
    AssertFailed {
        contract: String,
        circuit: String,
        message: String,
        depth: usize,
    },
}

/// Ordered sequence of [`TraceEvent`]s recorded during a single circuit or
/// call-tree execution.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionTrace {
    pub events: Vec<TraceEvent>,
}

impl ExecutionTrace {
    /// Create an empty trace buffer.
    #[must_use]
    pub const fn new() -> Self {
        Self { events: Vec::new() }
    }

    /// Returns `true` when no events have been recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Append one trace event.
    pub fn push(&mut self, event: TraceEvent) {
        self.events.push(event);
    }

    /// Clear all recorded events (used when a cross-contract call tree
    /// retries after binding a newly discovered callee).
    pub fn clear(&mut self) {
        self.events.clear();
    }

    /// Iterate over every witness observation recorded in this trace as
    /// `(contract, circuit, witness, observed_value)`.
    pub fn witness_observations(&self) -> impl Iterator<Item = (&str, &str, &str, &RuntimeValue)> {
        self.events.iter().filter_map(|ev| match ev {
            TraceEvent::WitnessCall {
                contract,
                circuit,
                witness,
                observed,
                ..
            } => Some((
                contract.as_str(),
                circuit.as_str(),
                witness.as_str(),
                observed,
            )),
            _ => None,
        })
    }

    /// Render the execution trace as an indented tree suitable for terminal
    /// diagnostics.
    #[must_use]
    pub fn render(&self) -> String {
        let mut out = String::new();
        for ev in &self.events {
            match ev {
                TraceEvent::CircuitEnter {
                    contract,
                    circuit,
                    args,
                    depth,
                } => {
                    let prefix = indent(*depth);
                    let _ = writeln!(
                        out,
                        "{prefix}{contract}.{circuit}({})",
                        format_args_compact(args)
                    );
                }
                TraceEvent::CircuitExit { result, depth, .. } => {
                    let prefix = child_indent(*depth);
                    let _ = writeln!(out, "{prefix}└─ return {}", format_value_compact(result));
                }
                TraceEvent::WitnessCall {
                    witness,
                    args,
                    observed,
                    depth,
                    ..
                } => {
                    let prefix = child_indent(*depth);
                    let _ = writeln!(
                        out,
                        "{prefix}├─ witness {witness}({}) => {}",
                        format_args_compact(args),
                        format_value_compact(observed)
                    );
                }
                TraceEvent::LedgerOp {
                    adt,
                    operation,
                    vm_op_count,
                    result,
                    depth,
                    ..
                } => {
                    let prefix = child_indent(*depth);
                    match result {
                        Some(val) => {
                            let _ = writeln!(
                                out,
                                "{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops) => {}",
                                format_value_compact(val)
                            );
                        }
                        None => {
                            let _ = writeln!(
                                out,
                                "{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops)"
                            );
                        }
                    }
                }
                TraceEvent::EmitEvent {
                    version,
                    tag,
                    depth,
                    ..
                } => {
                    let prefix = child_indent(*depth);
                    let _ = writeln!(out, "{prefix}├─ emit event(v{version}, tag={tag})");
                }
                TraceEvent::CrossContractCall {
                    callee,
                    circuit,
                    args,
                    depth,
                    ..
                } => {
                    let prefix = child_indent(*depth);
                    let _ = writeln!(
                        out,
                        "{prefix}├─ call {callee}.{circuit}({})",
                        format_args_compact(args)
                    );
                }
                TraceEvent::AssertFailed { message, depth, .. } => {
                    let prefix = child_indent(*depth);
                    let _ = writeln!(out, "{prefix}└─ [REVERT] assert failed: {message:?}");
                }
            }
        }
        out
    }
}

fn indent(depth: usize) -> String {
    "│  ".repeat(depth)
}

fn child_indent(depth: usize) -> String {
    format!("{}  ", "│  ".repeat(depth))
}

fn format_args_compact(args: &RuntimeValue) -> String {
    match args {
        RuntimeValue::Null => String::new(),
        RuntimeValue::Array(items) if items.is_empty() => String::new(),
        RuntimeValue::Array(items) => items
            .iter()
            .map(format_value_compact)
            .collect::<Vec<_>>()
            .join(", "),
        other => format_value_compact(other),
    }
}

/// Format a [`RuntimeValue`] concisely for trace display (truncating long
/// byte arrays and deeply nested containers).
#[must_use]
pub fn format_value_compact(val: &RuntimeValue) -> String {
    match val {
        RuntimeValue::Null => "()".to_owned(),
        RuntimeValue::Bool(b) => b.to_string(),
        RuntimeValue::Int(n) => n.to_string(),
        RuntimeValue::String(s) => {
            if s.len() > 48 {
                format!("\"{}…\" ({}B)", &s[..45], s.len())
            } else {
                format!("{s:?}")
            }
        }
        RuntimeValue::Bytes(bytes) => {
            if bytes.len() <= 8 {
                format!("0x{}", hex::encode(bytes))
            } else {
                format!(
                    "0x{}…{} ({}B)",
                    hex::encode(&bytes[..4]),
                    hex::encode(&bytes[bytes.len() - 2..]),
                    bytes.len()
                )
            }
        }
        RuntimeValue::Array(items) => {
            if items.is_empty() {
                "[]".to_owned()
            } else if items.len() <= 4 {
                let inner = items
                    .iter()
                    .map(format_value_compact)
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("[{inner}]")
            } else {
                format!(
                    "[{}, … ({} items)]",
                    format_value_compact(&items[0]),
                    items.len()
                )
            }
        }
        RuntimeValue::Object(map) => {
            let mut parts = Vec::new();
            for (i, (k, v)) in map.iter().enumerate() {
                if i >= 4 {
                    parts.push(format!("… ({} fields)", map.len()));
                    break;
                }
                parts.push(format!("{k}: {}", format_value_compact(v)));
            }
            format!("{{{}}}", parts.join(", "))
        }
    }
}

/// Short hex label for a contract address when no human contract name is set.
#[must_use]
pub(crate) fn short_address(
    addr: &moonproof_ledger::coin_structure::contract::ContractAddress,
) -> String {
    let hex_str = crate::state::contract_address_to_hex(addr);
    if hex_str.len() > 10 {
        format!("0x{}…{}", &hex_str[..6], &hex_str[hex_str.len() - 4..])
    } else {
        format!("0x{hex_str}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn trace_level_env_parsing() {
        assert_eq!(TraceLevel::from_env_str(""), TraceLevel::Off);
        assert_eq!(TraceLevel::from_env_str("0"), TraceLevel::Off);
        assert_eq!(TraceLevel::from_env_str("off"), TraceLevel::Off);
        assert_eq!(TraceLevel::from_env_str("calls"), TraceLevel::Calls);
        assert_eq!(TraceLevel::from_env_str("1"), TraceLevel::Full);
        assert_eq!(TraceLevel::from_env_str("full"), TraceLevel::Full);
        assert_eq!(TraceLevel::from_env_str("2"), TraceLevel::Full);
    }

    #[test]
    fn render_nested_call_tree_and_revert() {
        let mut trace = ExecutionTrace::new();
        trace.push(TraceEvent::CircuitEnter {
            contract: "vault".into(),
            circuit: "withdraw".into(),
            args: RuntimeValue::Int(100),
            depth: 0,
        });
        trace.push(TraceEvent::WitnessCall {
            contract: "vault".into(),
            circuit: "withdraw".into(),
            witness: "secret_key".into(),
            args: RuntimeValue::Null,
            observed: RuntimeValue::Bytes(vec![0xab; 32]),
            depth: 0,
        });
        trace.push(TraceEvent::LedgerOp {
            contract: "vault".into(),
            adt: "Counter".into(),
            operation: "increment".into(),
            vm_op_count: 3,
            result: None,
            depth: 0,
        });
        trace.push(TraceEvent::AssertFailed {
            contract: "vault".into(),
            circuit: "withdraw".into(),
            message: "insufficient balance".into(),
            depth: 0,
        });

        let rendered = trace.render();
        assert!(rendered.contains("vault.withdraw(100)"));
        assert!(rendered.contains("witness secret_key() => 0xabababab…abab (32B)"));
        assert!(rendered.contains("ledger Counter.increment (3 vm ops)"));
        assert!(rendered.contains("[REVERT] assert failed: \"insufficient balance\""));
        assert_eq!(trace.witness_observations().count(), 1);
    }
}