simplicityhl 0.5.0

Rust-like language that compiles to Simplicity bytecode.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use simplicity::bit_machine::{ExecTracker, FrameIter, NodeOutput, PruneTracker, SetTracker};
use simplicity::jet::{Elements, Jet};
use simplicity::node::Inner;
use simplicity::{Ihr, RedeemNode, Value as SimValue};

use crate::array::Unfolder;
use crate::debug::{DebugSymbols, TrackedCallName};
use crate::either::Either;
use crate::jet::{source_type, target_type};
use crate::str::AliasName;
use crate::types::AliasedType;
use crate::value::StructuralValue;
use crate::{ResolvedType, Value};

/// Callback signature for receiving debug output.
///
/// The first argument is the label (variable name or expression), and the second
/// is the formatted value.
type DebugSink<'a> = Box<dyn FnMut(&str, &Value) + 'a>;

/// Callback signature for receiving jet execution traces.
///
/// Arguments are: the jet that was executed, its input arguments (if successfully parsed),
/// and the result (`None` if the jet failed).
type JetTraceSink<'a> = Box<dyn FnMut(Elements, Option<&[Value]>, Option<Value>) + 'a>;

/// Callback signature for receiving warnings during execution.
type WarningSink<'a> = Box<dyn Fn(&str) + 'a>;

/// Controls the verbosity of program execution logging.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum TrackerLogLevel {
    #[default]
    None,
    Debug,
    Warning,
    Trace,
}

/// Default debug sink that prints labeled values to stderr.
fn default_debug_sink(label: &str, value: &Value) {
    println!("DBG: {label} = {value}");
}

/// Default jet trace sink that prints jet calls to stderr.
fn default_jet_trace_sink(jet: Elements, args: Option<&[Value]>, result: Option<Value>) {
    print!("{jet:?}(");
    if let Some(args) = args {
        for (i, arg) in args.iter().enumerate() {
            if i > 0 {
                print!(", ");
            }
            print!("{arg}");
        }
    } else {
        print!("...");
    }

    match result {
        Some(value) => println!(") = {value}"),
        None => println!(") -> [failed]"),
    }
}

/// Default warning sink that prints warnings to stderr.
fn default_warning_sink(message: &str) {
    println!("WARN: {message}");
}

/// Tracker for introspecting SimplicityHL program execution.
///
/// This tracker extends [`SetTracker`] with SimplicityHL-specific functionality:
///
/// - Decodes and forwards `dbg!()` calls to a configurable sink, using
///   the provided [`DebugSymbols`] to resolve CMRs to debug information.
/// - Optionally traces jet invocations with decoded arguments and return values.
///
/// # Example
///
/// ```rust,ignore
/// let tracker = DefaultTracker::new(&debug_symbols)
///     .with_log_level(TrackerLogLevel::Debug);
///
/// let pruned = program.prune_with_tracker(&env, &mut tracker)?;
/// ```
pub struct DefaultTracker<'a> {
    debug_symbols: &'a DebugSymbols,
    debug_sink: Option<DebugSink<'a>>,
    jet_trace_sink: Option<JetTraceSink<'a>>,
    warning_sink: Option<WarningSink<'a>>,
    inner: SetTracker,
}

impl<'a> DefaultTracker<'a> {
    /// Creates a new tracker bound to the given debug symbol table.
    pub fn new(debug_symbols: &'a DebugSymbols) -> Self {
        Self {
            debug_symbols,
            debug_sink: None,
            jet_trace_sink: None,
            warning_sink: None,
            inner: SetTracker::default(),
        }
    }

    /// Enables forwarding of `debug!()` calls to the provided sink.
    pub fn with_debug_sink<F>(mut self, sink: F) -> Self
    where
        F: FnMut(&str, &Value) + 'a,
    {
        self.debug_sink = Some(Box::new(sink));
        self
    }

    /// Enables the default debug sink that prints to stderr.
    pub fn with_default_debug_sink(self) -> Self {
        self.with_debug_sink(default_debug_sink)
    }

    /// Enables forwarding of jet call traces to the provided sink.
    pub fn with_jet_trace_sink<F>(mut self, sink: F) -> Self
    where
        F: FnMut(Elements, Option<&[Value]>, Option<Value>) + 'a,
    {
        self.jet_trace_sink = Some(Box::new(sink));
        self
    }

    /// Enables the default jet trace sink that prints to stderr.
    pub fn with_default_jet_trace_sink(self) -> Self {
        self.with_jet_trace_sink(default_jet_trace_sink)
    }

    /// Enables forwarding of warnings to the provided sink.
    pub fn with_warning_sink<F>(mut self, sink: F) -> Self
    where
        F: Fn(&str) + 'a,
    {
        self.warning_sink = Some(Box::new(sink));
        self
    }

    /// Enables the default warning sink that prints to stderr.
    pub fn with_default_warning_sink(self) -> Self {
        self.with_warning_sink(default_warning_sink)
    }

    /// Configures the tracker based on the specified log level.
    ///
    /// - [`TrackerLogLevel::None`]: No sinks enabled.
    /// - [`TrackerLogLevel::Debug`]: Default debug sink enabled.
    /// - [`TrackerLogLevel::Warning`]: Default debug and warning sinks enabled.
    /// - [`TrackerLogLevel::Trace`]: Default debug, warning, and jet trace sinks enabled.
    pub fn with_log_level(self, log_level: TrackerLogLevel) -> Self {
        let tracker = if log_level >= TrackerLogLevel::Debug {
            self.with_default_debug_sink()
        } else {
            self
        };

        let tracker = if log_level >= TrackerLogLevel::Warning {
            tracker.with_default_warning_sink()
        } else {
            tracker
        };

        if log_level >= TrackerLogLevel::Trace {
            tracker.with_default_jet_trace_sink()
        } else {
            tracker
        }
    }

    /// Handles jet node execution by decoding arguments and results.
    fn handle_jet(
        &mut self,
        node: &RedeemNode<Elements>,
        jet: Elements,
        input: &FrameIter,
        output: &NodeOutput,
    ) {
        if self.jet_trace_sink.is_none() {
            return;
        }

        let mut input_frame = input.clone();

        // The reason we need to advance by a bit is that the AssertL combinator is actually a Case combinator,
        // which takes a bit of input to decide which branch to take. But this bit is "meaningless" and
        // is always 0 because it's an assertion.
        let _ = input_frame.next();

        let args = match parse_jet_arguments(jet, &mut input_frame) {
            Ok(args) => args,
            Err(e) => {
                self.warn(&format!("Failed to parse arguments for jet {jet:?}: {e}"));

                // Still call the sink to report the jet execution, but without arguments.
                let result = Self::parse_jet_result(node, jet, output);
                if let Some(sink) = self.jet_trace_sink.as_mut() {
                    sink(jet, None, result);
                }

                return;
            }
        };

        let result = Self::parse_jet_result(node, jet, output);

        if let Some(sink) = self.jet_trace_sink.as_mut() {
            sink(jet, Some(&args), result);
        }
    }

    /// Parses the result of a jet execution from the output frame.
    fn parse_jet_result(
        node: &RedeemNode<Elements>,
        jet: Elements,
        output: &NodeOutput,
    ) -> Option<Value> {
        match output.clone() {
            NodeOutput::Success(mut output_frame) => {
                let target_ty = &node.arrow().target;
                let jet_target_ty = resolve_jet_type(&target_type(jet));

                // Skip the leading bit when the frame has extra padding.
                // This occurs because some jets (like eq_64 etc.) are wrapped in AssertL (a Case combinator),
                // see compile::with_debug_symbol
                if target_ty.as_sum().is_some() {
                    let _ = output_frame.next();
                }

                let output_value = SimValue::from_padded_bits(&mut output_frame, target_ty)
                    .expect("output from bit machine is always well-formed");

                Value::reconstruct(&StructuralValue::from(output_value), &jet_target_ty)
            }
            _ => None,
        }
    }

    /// Sends a warning to the warning sink if configured.
    fn warn(&self, message: &str) {
        if let Some(sink) = self.warning_sink.as_ref() {
            sink(message);
        }
    }

    /// Handles debug node execution by resolving symbols and decoding values.
    fn handle_debug(
        &mut self,
        node: &RedeemNode<Elements>,
        input: &FrameIter,
        cmr: &simplicity::Cmr,
    ) {
        if self.debug_sink.is_none() {
            return;
        }

        let Some(tracked_call) = self.debug_symbols.get(cmr) else {
            self.warn(&format!("Unknown debug symbol: CMR {cmr}"));
            return;
        };

        let TrackedCallName::Debug(_) = tracked_call.name() else {
            return;
        };

        let mut input_frame = input.clone();

        // Skip the Case combinator's branch selection bit (see handle_jet).
        let _ = input_frame.next();

        // The debug call has signature `dbg!(T) -> T`, so the target type
        // matches the value being debugged
        let Ok(input_val) = SimValue::from_padded_bits(&mut input_frame, &node.arrow().target)
        else {
            self.warn(&format!("Failed to decode debug value for CMR {cmr}"));
            return;
        };

        let Some(Either::Right(debug_value)) =
            tracked_call.map_value(&StructuralValue::from(input_val))
        else {
            return;
        };

        if let Some(sink) = self.debug_sink.as_mut() {
            sink(debug_value.text(), debug_value.value());
        }
    }
}

impl PruneTracker<Elements> for DefaultTracker<'_> {
    fn contains_left(&self, ihr: Ihr) -> bool {
        if PruneTracker::<Elements>::contains_left(&self.inner, ihr) {
            return true;
        }

        if let Some(sink) = self.warning_sink.as_ref() {
            sink(&format!("Pruning unexecuted left child of IHR {ihr}"));
        }

        false
    }

    fn contains_right(&self, ihr: Ihr) -> bool {
        if PruneTracker::<Elements>::contains_right(&self.inner, ihr) {
            return true;
        }

        if let Some(sink) = self.warning_sink.as_ref() {
            sink(&format!("Pruning unexecuted right child of IHR {ihr}"));
        }

        false
    }
}

impl ExecTracker<Elements> for DefaultTracker<'_> {
    fn visit_node(&mut self, node: &RedeemNode<Elements>, input: FrameIter, output: NodeOutput) {
        match node.inner() {
            Inner::Jet(jet) => self.handle_jet(node, *jet, &input, &output),
            Inner::AssertL(_, cmr) => self.handle_debug(node, &input, cmr),
            _ => {}
        }

        self.inner.visit_node(node, input, output);
    }
}

/// Parses jet input arguments from the bit machine's read frame.
fn parse_jet_arguments(jet: Elements, input_frame: &mut FrameIter) -> Result<Vec<Value>, String> {
    let source_types = source_type(jet);
    if source_types.is_empty() {
        return Ok(vec![]);
    }

    let arguments_blob = SimValue::from_padded_bits(input_frame, &jet.source_ty().to_final())
        .expect("input from bit machine is always well-formed");

    let args = Unfolder::new(arguments_blob.as_ref(), source_types.len())
        .unfold(|v| v.as_product())
        .ok_or("expected product type while collecting arguments")?;

    Ok(args
        .into_iter()
        .zip(source_types.iter())
        .map(|(arg, aliased_type)| {
            Value::reconstruct(&arg.to_value().into(), &resolve_jet_type(aliased_type))
                .expect("compiled program produces correctly structured values")
        })
        .collect())
}

/// Resolves an aliased type to its concrete form.
fn resolve_jet_type(aliased_type: &AliasedType) -> ResolvedType {
    aliased_type
        .resolve(|_: &AliasName| None)
        .expect("jet types always resolve without aliases")
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use std::sync::Arc;

    use simplicity::elements::taproot::ControlBlock;
    use simplicity::elements::BlockHash;
    use simplicity::elements::{self, pset::PartiallySignedTransaction};
    use simplicity::jet::elements::{ElementsEnv, ElementsUtxo};
    use simplicity::Cmr;

    use crate::elements::confidential::Asset;
    use crate::elements::hashes::Hash;
    use crate::elements::pset::Input;
    use crate::elements::{AssetId, OutPoint, Script, Txid};
    use crate::{Arguments, TemplateProgram, WitnessValues};

    use super::*;

    const TEST_PROGRAM: &str = r#"
        fn get_input_explicit_asset_amount(index: u32) -> (u256, u64) {
            let pair: (Asset1, Amount1) = unwrap(jet::input_amount(index));
            let (asset, amount): (Asset1, Amount1) = dbg!(pair);
            let asset_bits: u256 = unwrap_right::<(u1, u256)>(asset);
            let amount: u64 = unwrap_right::<(u1, u256)>(amount);
            (asset_bits, amount)
        }

        fn main() {
            let a: u32 = jet::num_inputs();
            let b: bool = dbg!(jet::eq_32(20, 21));
            let c: (u256, u64) = dbg!(get_input_explicit_asset_amount(0));
        }
    "#;

    type DebugStore = Rc<RefCell<HashMap<String, String>>>;
    type JetStore = Rc<RefCell<HashMap<String, (Option<Vec<String>>, Option<String>)>>>;

    fn create_test_tracker(
        debug_symbols: &DebugSymbols,
    ) -> (DefaultTracker<'_>, DebugStore, JetStore) {
        let debug_store: DebugStore = Rc::default();
        let jet_store: JetStore = Rc::default();

        let debug_clone = debug_store.clone();
        let jet_clone = jet_store.clone();

        let tracker = DefaultTracker::new(debug_symbols)
            .with_debug_sink(move |label, value| {
                debug_clone
                    .borrow_mut()
                    .insert(label.to_string(), value.to_string());
            })
            .with_jet_trace_sink(move |jet, args, result| {
                jet_clone.borrow_mut().insert(
                    jet.to_string(),
                    (
                        args.map(|a| a.iter().map(|v| v.to_string()).collect()),
                        result.map(|r| r.to_string()),
                    ),
                );
            });

        (tracker, debug_store, jet_store)
    }

    fn create_test_env() -> ElementsEnv<Arc<elements::Transaction>> {
        let mut tx = PartiallySignedTransaction::new_v2();
        let outpoint = OutPoint::new(Txid::from_slice(&[2; 32]).unwrap(), 33);
        tx.add_input(Input::from_prevout(outpoint));

        ElementsEnv::new(
            Arc::new(tx.extract_tx().unwrap()),
            vec![ElementsUtxo {
                script_pubkey: Script::new(),
                asset: Asset::Explicit(AssetId::LIQUID_BTC),
                value: elements::confidential::Value::Explicit(1000),
            }],
            0,
            Cmr::from_byte_array([0; 32]),
            ControlBlock::from_slice(&[0xc0; 33]).unwrap(),
            None,
            BlockHash::all_zeros(),
        )
    }

    #[test]
    fn test_debug_and_jet_tracing() {
        let program = TemplateProgram::new(TEST_PROGRAM).unwrap();
        let program = program.instantiate(Arguments::default(), true).unwrap();
        let satisfied = program.satisfy(WitnessValues::default()).unwrap();

        let (mut tracker, debug_store, jet_store) = create_test_tracker(&satisfied.debug_symbols);
        let env = create_test_env();

        let _ = satisfied
            .redeem()
            .prune_with_tracker(&env, &mut tracker)
            .unwrap();

        let debug = debug_store.borrow();
        assert_eq!(
            debug.get("get_input_explicit_asset_amount(0)"),
            Some(
                &"(0x6d521c38ec1ea15734ae22b7c46064412829c0d0579f0a713d1c04ede979026f, 1000)"
                    .to_string()
            ),
        );
        assert_eq!(
            debug.get("pair"),
            Some(
                &"(Right(0x6d521c38ec1ea15734ae22b7c46064412829c0d0579f0a713d1c04ede979026f), Right(1000))"
                    .to_string()
            ),
        );
        assert_eq!(debug.get("jet::eq_32(20, 21)"), Some(&"false".to_string()));

        let jets = jet_store.borrow();

        assert_eq!(
            jets.get("num_inputs").unwrap().0.as_deref(),
            Some([].as_slice())
        );
        assert_eq!(jets.get("num_inputs").unwrap().1.as_deref(), Some("1"));

        assert_eq!(
            jets.get("eq_32").unwrap().0,
            Some(vec!["20".to_string(), "21".to_string()])
        );
        assert_eq!(jets.get("eq_32").unwrap().1.as_deref(), Some("false"));

        assert_eq!(
            jets.get("input_amount").unwrap().0,
            Some(vec!["0".to_string()])
        );
        assert_eq!(
            jets.get("input_amount").unwrap().1.as_deref(),
            Some("Some((Right(0x6d521c38ec1ea15734ae22b7c46064412829c0d0579f0a713d1c04ede979026f), Right(1000)))")
        );
    }
    const TEST_ARITHMETIC_JETS: &str = r#"
        fn main() {

            let x: u32 = 5;
            let y: u32 = 4;

            let sum: (bool, u32) = jet::add_32(x, y);
            let prod: u64 = jet::multiply_32(x, y);

            assert!(jet::eq_64(prod, 20));
        }
    "#;

    #[test]
    fn test_arith_jet_trace_regression() {
        let env = create_test_env();

        let program = TemplateProgram::new(TEST_ARITHMETIC_JETS).unwrap();
        let program = program.instantiate(Arguments::default(), true).unwrap();
        let satisfied = program.satisfy(WitnessValues::default()).unwrap();

        let (mut tracker, _, jet_store) = create_test_tracker(&satisfied.debug_symbols);

        let _ = satisfied.redeem().prune_with_tracker(&env, &mut tracker);

        let jets = jet_store.borrow();

        assert_eq!(
            jets.get("add_32").unwrap().0,
            Some(vec!["5".to_string(), "4".to_string()])
        );
        assert_eq!(
            jets.get("add_32").unwrap().1,
            Some("(false, 9)".to_string())
        );

        assert_eq!(
            jets.get("multiply_32").unwrap().0,
            Some(vec!["5".to_string(), "4".to_string()])
        );
        assert_eq!(jets.get("multiply_32").unwrap().1, Some("20".to_string()));

        assert_eq!(
            jets.get("eq_64").unwrap().0,
            Some(vec!["20".to_string(), "20".to_string()])
        );
        assert_eq!(jets.get("eq_64").unwrap().1, Some("true".to_string()));
    }

    const TEST_FULL_MULTIPLY_JETS: &str = r#"
    fn main() {
        let r8: u16 = jet::full_multiply_8(200, 201, 202, 203);
        let r16: u32 = jet::full_multiply_16(20000, 20001, 20002, 20003);
        let r32: u64 = jet::full_multiply_32(2000000000, 2000000001, 2000000002, 2000000003);
        let r64: u128 = jet::full_multiply_64(2000000000, 2000000001, 2000000002, 2000000003);

        assert!(jet::eq_16(r8, 40605));
        assert!(jet::eq_32(r16, 400060005));
        assert!(jet::eq_64(r32, 4000000006000000005));

        // TODO: Currently no eq_128 jet, this must be revised in future. Placeholder to match on 'unwrap().1`.
        let _keep: u128 = r64;
    }
    "#;

    #[test]
    fn test_full_multiply_jet_trace_regression() {
        // FullMultiply -> (a * b + c + d)

        let env = create_test_env();

        let program = TemplateProgram::new(TEST_FULL_MULTIPLY_JETS).unwrap();
        let program = program.instantiate(Arguments::default(), true).unwrap();
        let satisfied = program.satisfy(WitnessValues::default()).unwrap();

        let (mut tracker, _, jet_store) = create_test_tracker(&satisfied.debug_symbols);

        let _ = satisfied.redeem().prune_with_tracker(&env, &mut tracker);

        let jets = jet_store.borrow();

        assert_eq!(
            jets.get("full_multiply_8").unwrap().0,
            Some(vec![
                "200".to_string(),
                "201".to_string(),
                "202".to_string(),
                "203".to_string(),
            ])
        );
        assert_eq!(
            jets.get("full_multiply_8").unwrap().1,
            Some("40605".to_string())
        );

        assert_eq!(
            jets.get("full_multiply_16").unwrap().0,
            Some(vec![
                "20000".to_string(),
                "20001".to_string(),
                "20002".to_string(),
                "20003".to_string(),
            ])
        );
        assert_eq!(
            jets.get("full_multiply_16").unwrap().1,
            Some("400060005".to_string())
        );

        assert_eq!(
            jets.get("full_multiply_32").unwrap().0,
            Some(vec![
                "2000000000".to_string(),
                "2000000001".to_string(),
                "2000000002".to_string(),
                "2000000003".to_string(),
            ])
        );
        assert_eq!(
            jets.get("full_multiply_32").unwrap().1,
            Some("4000000006000000005".to_string())
        );

        assert_eq!(
            jets.get("full_multiply_64").unwrap().0,
            Some(vec![
                "2000000000".to_string(),
                "2000000001".to_string(),
                "2000000002".to_string(),
                "2000000003".to_string(),
            ])
        );
        assert_eq!(
            jets.get("full_multiply_64").unwrap().1,
            // Check: u128 defaults to hex in fmt::Display for UIntValue
            Some("0x00000000000000003782dad00330bc05".to_string()) // u128 => 4000000006000000005
        );
    }
}