simplicityhl_core/
runner.rs

1//! Program execution helpers and logging levels for Simplicity programs.
2//!
3//! Provides `run_program` which satisfies and executes a compiled program
4//! against an `ElementsEnv`, with optional debug and jet-trace logging.
5
6use crate::DefaultTracker;
7
8use std::sync::Arc;
9
10use simplicityhl::simplicity::elements::Transaction;
11use simplicityhl::simplicity::jet::Elements;
12use simplicityhl::simplicity::jet::elements::ElementsEnv;
13use simplicityhl::simplicity::{BitMachine, RedeemNode, Value};
14use simplicityhl::{CompiledProgram, WitnessValues};
15
16/// Controls verbosity of program execution.
17#[derive(PartialEq, Eq, PartialOrd, Ord, Default, Copy, Clone, Debug)]
18pub enum RunnerLogLevel {
19    #[default]
20    None,
21    Debug,
22    Trace,
23}
24
25/// Satisfy and execute a compiled program in the provided environment.
26/// Returns the pruned program and the resulting value.
27pub fn run_program(
28    program: &CompiledProgram,
29    witness_values: WitnessValues,
30    env: ElementsEnv<Arc<Transaction>>,
31    log_level: RunnerLogLevel,
32) -> anyhow::Result<(Arc<RedeemNode<Elements>>, Value)> {
33    let satisfied = program
34        .satisfy(witness_values)
35        .map_err(|e| anyhow::anyhow!("{}", e))?;
36
37    let pruned = match satisfied.redeem().prune(&env) {
38        Ok(pruned) => pruned,
39        Err(e) => return Err(e.into()),
40    };
41    let mut mac = match BitMachine::for_program(&pruned) {
42        Ok(mac) => mac,
43        Err(e) => return Err(e.into()),
44    };
45
46    let mut tracker = {
47        let mut t = DefaultTracker::new(satisfied.debug_symbols());
48        if log_level >= RunnerLogLevel::Debug {
49            t = t.with_default_debug_sink();
50        }
51        if log_level >= RunnerLogLevel::Trace {
52            t = t.with_default_jet_trace_sink();
53        }
54        t
55    };
56
57    match mac.exec_with_tracker(&pruned, &env, &mut tracker) {
58        Ok(res) => Ok((pruned, res)),
59        Err(e) => Err(e.into()),
60    }
61}