Skip to main content

smplx_sdk_test/program/
logger.rs

1use std::collections::HashMap;
2use std::{cell::RefCell, fmt::Write};
3
4use simplicityhl::ast::ElementsJetHinter;
5use simplicityhl::debug::DebugSymbols;
6use simplicityhl::simplicity::node::{Node, Redeem};
7use simplicityhl::tracker::{DefaultTracker, TrackerLogLevel};
8
9thread_local! {
10    pub(super) static PROGRAM_LOGGER: RefCell<ProgramLogger> = RefCell::new(ProgramLogger { logs: HashMap::new() });
11}
12
13/// Helper struct for gathering info from `node.bounds()`.
14pub struct CostInfo {
15    /// truncated cmr
16    pub cmr: [u8; 8],
17    /// inner value of `Cost`
18    pub cost: u32,
19    /// program size in bytes
20    pub program_size: usize,
21    /// witness size in bytes
22    pub witness_size: usize,
23}
24
25/// Helper struct for gathering info about a specific program execution.
26#[derive(Default)]
27pub struct ProgramInfo {
28    /// Cost metrics from the most recent program execution.
29    pub cost_info: Option<CostInfo>,
30    /// Execution trace lines in insertion order.
31    pub trace_buffer: Vec<String>,
32}
33
34/// Logger state for buffering execution output.
35///
36/// Buffers are flushed to stderr only on successful transaction finalization,
37/// discarding output from intermediate estimation passes.
38pub struct ProgramLogger {
39    /// A mapping of program ids to program logs
40    pub logs: HashMap<usize, ProgramInfo>,
41}
42
43impl ProgramLogger {
44    /// Mirrors [`DefaultTracker::with_log_level`] with buffered sinks instead of stderr.
45    /// Clears any previously buffered `input_index` logs before configuring the tracker.
46    #[must_use]
47    pub fn make_tracker(
48        input_index: usize,
49        debug_symbols: &DebugSymbols,
50        log_level: TrackerLogLevel,
51    ) -> DefaultTracker<'_> {
52        Self::clear_program_logs(input_index);
53
54        let tracker = DefaultTracker::build(debug_symbols, Box::new(ElementsJetHinter));
55
56        let tracker = if log_level >= TrackerLogLevel::Debug {
57            tracker.with_debug_sink(move |label, value| {
58                Self::buffer_trace_log(input_index, format!("  DBG: {label} = {value}"));
59            })
60        } else {
61            tracker
62        };
63
64        let tracker = if log_level >= TrackerLogLevel::Warning {
65            tracker.with_warning_sink(move |msg| {
66                Self::buffer_trace_log(input_index, format!("  WARN: {msg}"));
67            })
68        } else {
69            tracker
70        };
71
72        if log_level >= TrackerLogLevel::Trace {
73            tracker.with_jet_trace_sink(move |jet, args, result| {
74                let mut msg = format!("  {jet:?}(");
75
76                if let Some(args) = args {
77                    for (i, arg) in args.iter().enumerate() {
78                        if i > 0 {
79                            msg.push_str(", ");
80                        }
81                        let _ = write!(msg, "{arg}");
82                    }
83                } else {
84                    msg.push_str("...");
85                }
86
87                match result {
88                    Some(value) => {
89                        let _ = write!(msg, ") = {value}");
90                    }
91                    None => msg.push_str(") -> [failed]"),
92                }
93
94                Self::buffer_trace_log(input_index, msg);
95            })
96        } else {
97            tracker
98        }
99    }
100
101    /// Buffers a line of execution trace output.
102    pub fn buffer_trace_log(input_index: usize, tracker_logs: String) {
103        PROGRAM_LOGGER.with(|logger| {
104            let mut logger = logger.borrow_mut();
105            let program_log = logger.logs.entry(input_index).or_insert(ProgramInfo::default());
106
107            program_log.trace_buffer.push(tracker_logs);
108        });
109    }
110
111    /// Extracts and buffers cost metrics from the given redeem node.
112    ///
113    /// Overwrites any previously buffered cost info.
114    ///
115    /// # Safety
116    /// Uses `transmute` to extract the inner `u32` from [`Cost`] since no public
117    /// accessor exists. Remove once `as_milliweight()` is upstreamed to rust-simplicity.
118    pub fn buffer_cost_log(input_index: usize, node: &Node<Redeem>) {
119        let bounds = node.bounds();
120        // FIXME: Cost has no public accessor; remove once as_milliweight() is upstreamed
121        let mw: u32 = unsafe { std::mem::transmute(bounds.cost) };
122        let encoded = node.to_vec_with_witness();
123        let (program_size, witness_size) = (encoded.0.len(), encoded.1.len());
124        let cmr_bytes = node.cmr().to_byte_array();
125
126        PROGRAM_LOGGER.with(|logger| {
127            let mut logger = logger.borrow_mut();
128            let program_log = logger.logs.entry(input_index).or_insert(ProgramInfo::default());
129
130            program_log.cost_info = Some(CostInfo {
131                cmr: std::array::from_fn(|i| cmr_bytes[i]),
132                cost: mw / 1000,
133                program_size,
134                witness_size,
135            });
136        });
137    }
138
139    /// Flushes all buffered cost and trace output to stderr, then clears buffers.
140    ///
141    /// Cost metrics are printed first, followed by execution trace lines in
142    /// insertion order.
143    ///
144    /// Call this on successful transaction finalization.
145    pub fn flush_logs() {
146        PROGRAM_LOGGER.with(|logger| {
147            let logger = logger.borrow();
148
149            for (input_index, program_log) in &logger.logs {
150                if let Some(cost_info) = &program_log.cost_info {
151                    let cmr_hex: String = cost_info.cmr.iter().fold(String::new(), |mut output, b| {
152                        let _ = write!(output, "{b:02x}");
153                        output
154                    });
155
156                    eprintln!(
157                        "Program info: input={}  cmr=[{}]  cost={}wu  prog={}b  witness={}b",
158                        input_index, cmr_hex, cost_info.cost, cost_info.program_size, cost_info.witness_size,
159                    );
160                }
161
162                if !program_log.trace_buffer.is_empty() {
163                    eprintln!("───────────── trace ─────────────");
164
165                    for msg in &program_log.trace_buffer {
166                        eprintln!("{msg}");
167                    }
168
169                    eprintln!();
170                }
171            }
172        });
173
174        Self::clear_logs();
175    }
176
177    /// Discards specific program buffered output without printing.
178    pub fn clear_program_logs(input_index: usize) {
179        PROGRAM_LOGGER.with(|logger| {
180            logger.borrow_mut().logs.remove(&input_index);
181        });
182    }
183
184    /// Discards all buffered output without printing.
185    pub fn clear_logs() {
186        PROGRAM_LOGGER.with(|logger| {
187            logger.borrow_mut().logs.clear();
188        });
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn buffered_logs_can_be_cleared_per_program_or_globally() {
198        ProgramLogger::clear_logs();
199        ProgramLogger::buffer_trace_log(1, "first".to_string());
200        ProgramLogger::buffer_trace_log(2, "second".to_string());
201
202        PROGRAM_LOGGER.with(|logger| assert_eq!(logger.borrow().logs.len(), 2));
203
204        ProgramLogger::clear_program_logs(1);
205
206        PROGRAM_LOGGER.with(|logger| assert!(!logger.borrow().logs.contains_key(&1)));
207        PROGRAM_LOGGER.with(|logger| {
208            let logger = logger.borrow();
209            assert_eq!(logger.logs.len(), 1);
210            assert!(logger.logs.contains_key(&2));
211        });
212
213        ProgramLogger::clear_logs();
214
215        PROGRAM_LOGGER.with(|logger| assert!(logger.borrow().logs.is_empty()));
216    }
217}