Skip to main content

smplx_sdk_test/program/
core.rs

1use std::sync::{Arc, OnceLock};
2
3use bitcoin_hashes::Hash;
4use dyn_clone::DynClone;
5
6use simplicityhl::ast::ElementsJetHinter;
7use simplicityhl::elements::pset::PartiallySignedTransaction;
8use simplicityhl::elements::{Address, Script, Transaction, TxOut, taproot};
9use simplicityhl::simplicity::bitcoin::{XOnlyPublicKey, secp256k1};
10use simplicityhl::simplicity::jet::elements::{ElementsEnv, ElementsUtxo};
11use simplicityhl::simplicity::{BitMachine, RedeemNode, Value, leaf_version};
12use simplicityhl::{Arguments, Parameters, WitnessTypes, WitnessValues};
13use simplicityhl::{CompiledProgram, UnstableFeatures};
14
15use crate::global::GlobalConfig;
16use crate::program::logger::ProgramLogger;
17
18use super::arguments::ArgumentsTrait;
19use super::error::ProgramError;
20
21use crate::provider::SimplicityNetwork;
22use crate::utils::{hash_script, tap_data_hash, tr_unspendable_key};
23
24/// Executes `simplicity` programs at runtime.
25///
26/// This trait defines a core behavior related to testing and execution.
27pub trait ProgramTrait: DynClone {
28    /// Retrieves the types of arguments required by a `simplicity` program.
29    ///
30    /// # Errors
31    /// Returns a `ProgramError` if parsing or generating ABI metadata fails.
32    fn get_argument_types(&self) -> Result<Parameters, ProgramError>;
33
34    /// Retrieves the witness types required by a `simplicity` program.
35    ///
36    /// # Errors
37    /// Returns a `ProgramError` if parsing or generating ABI metadata fails.
38    fn get_witness_types(&self) -> Result<WitnessTypes, ProgramError>;
39
40    /// Constructs the Elements environment for a specified input index, PST, and network for further program execution.
41    ///
42    /// # Errors
43    /// Returns a `ProgramError` if the input index is out of bounds or if the script pubkey of the UTXO mismatches the expected program script.
44    fn get_env(
45        &self,
46        pst: &PartiallySignedTransaction,
47        input_index: usize,
48        network: &SimplicityNetwork,
49    ) -> Result<ElementsEnv<Arc<Transaction>>, ProgramError>;
50
51    /// Executes a Simplicity program for the given input index of a partially signed transaction.
52    ///
53    /// This function evaluates a Simplicity script associated with a specific transaction input
54    /// in a given network, producing the result of the computation along with the redeem node
55    /// used during execution.
56    ///
57    /// # Errors
58    /// Returns a `ProgramError` if loading the program, satisfying the witness, retrieving the environment, or executing the `BitMachine` fails.
59    fn execute(
60        &self,
61        pst: &PartiallySignedTransaction,
62        witness: &WitnessValues,
63        input_index: usize,
64        network: &SimplicityNetwork,
65    ) -> Result<(Arc<RedeemNode>, Value), ProgramError>;
66
67    /// Finalizes and returns `pruned_witness` as output after executing the program on certain parameters.
68    ///
69    /// # Errors
70    /// Returns a `ProgramError` if program execution or constructing the control block fails.
71    fn finalize(
72        &self,
73        pst: &PartiallySignedTransaction,
74        witness: &WitnessValues,
75        input_index: usize,
76        network: &SimplicityNetwork,
77    ) -> Result<Vec<Vec<u8>>, ProgramError>;
78}
79
80/// Represents a program structure containing its public key, compiled program, and associated storage.
81/// A compiled program acts as a cache, instantiated during "loading".
82///
83/// Abstraction giving the power to execute Simplicity contracts without specifying any additional parameters.
84#[derive(Clone)]
85pub struct Program {
86    source: Arc<str>,
87    arguments: Arguments,
88    pub_key: XOnlyPublicKey,
89    storage: Vec<Vec<u8>>,
90    include_debug_symbols: Option<bool>,
91    compiled: Arc<OnceLock<CompiledProgram>>,
92}
93
94dyn_clone::clone_trait_object!(ProgramTrait);
95
96impl ProgramTrait for Program {
97    fn get_argument_types(&self) -> Result<Parameters, ProgramError> {
98        self.get_argument_types()
99    }
100
101    fn get_witness_types(&self) -> Result<WitnessTypes, ProgramError> {
102        self.get_witness_types()
103    }
104
105    fn get_env(
106        &self,
107        pst: &PartiallySignedTransaction,
108        input_index: usize,
109        network: &SimplicityNetwork,
110    ) -> Result<ElementsEnv<Arc<Transaction>>, ProgramError> {
111        let genesis_hash = network.genesis_block_hash();
112        let cmr = self.load()?.commit().cmr();
113        let utxos: Vec<TxOut> = pst.inputs().iter().filter_map(|x| x.witness_utxo.clone()).collect();
114
115        if utxos.len() <= input_index {
116            return Err(ProgramError::UtxoIndexOutOfBounds {
117                input_index,
118                utxo_count: utxos.len(),
119            });
120        }
121
122        let target_utxo = &utxos[input_index];
123        let script_pubkey = self.get_tr_address(network).script_pubkey();
124
125        if target_utxo.script_pubkey != script_pubkey {
126            return Err(ProgramError::ScriptPubkeyMismatch {
127                expected_hash: script_pubkey.script_hash().to_string(),
128                actual_hash: target_utxo.script_pubkey.script_hash().to_string(),
129            });
130        }
131
132        Ok(ElementsEnv::new(
133            Arc::new(pst.extract_tx()?),
134            utxos
135                .iter()
136                .map(|utxo| ElementsUtxo {
137                    script_pubkey: utxo.script_pubkey.clone(),
138                    asset: utxo.asset,
139                    value: utxo.value,
140                })
141                .collect(),
142            u32::try_from(input_index)?,
143            cmr,
144            self.control_block()?,
145            None,
146            genesis_hash,
147        ))
148    }
149
150    fn execute(
151        &self,
152        pst: &PartiallySignedTransaction,
153        witness: &WitnessValues,
154        input_index: usize,
155        network: &SimplicityNetwork,
156    ) -> Result<(Arc<RedeemNode>, Value), ProgramError> {
157        let satisfied = self
158            .load()?
159            .satisfy(witness.clone())
160            .map_err(ProgramError::WitnessSatisfaction)?;
161
162        // execute() is called multiple times during fee estimation; output is buffered
163        // so only the final successful execution's logs are emitted to stderr.
164        let mut tracker =
165            ProgramLogger::make_tracker(input_index, satisfied.debug_symbols(), GlobalConfig::get_log_level());
166
167        let env = self.get_env(pst, input_index, network)?;
168
169        let pruned = satisfied.redeem().prune_with_tracker(&env, &mut tracker)?;
170
171        if GlobalConfig::is_max_verbose() {
172            ProgramLogger::buffer_cost_log(input_index, &pruned);
173        }
174
175        let mut mac = BitMachine::for_program(&pruned)?;
176
177        let result = mac.exec(&pruned, &env)?;
178
179        Ok((pruned, result))
180    }
181
182    fn finalize(
183        &self,
184        pst: &PartiallySignedTransaction,
185        witness: &WitnessValues,
186        input_index: usize,
187        network: &SimplicityNetwork,
188    ) -> Result<Vec<Vec<u8>>, ProgramError> {
189        let pruned = self.execute(pst, witness, input_index, network)?.0;
190
191        let (simplicity_program_bytes, simplicity_witness_bytes) = pruned.to_vec_with_witness();
192        let cmr = pruned.cmr();
193
194        Ok(vec![
195            simplicity_witness_bytes,
196            simplicity_program_bytes,
197            cmr.as_ref().to_vec(),
198            self.control_block()?.serialize(),
199        ])
200    }
201}
202
203impl Program {
204    /// The width of a storage slot.
205    pub const STORAGE_SLOT_BYTES: usize = 32;
206
207    /// Creates a new instance of the struct with the provided source string and arguments.
208    #[must_use]
209    pub fn new(source: impl Into<Arc<str>>, arguments: &dyn ArgumentsTrait) -> Self {
210        Self {
211            source: source.into(),
212            pub_key: tr_unspendable_key(),
213            arguments: arguments.build_arguments(),
214            storage: Vec::new(),
215            include_debug_symbols: None,
216            compiled: Arc::new(OnceLock::new()),
217        }
218    }
219
220    /// Sets the `pub_key` field of the struct to the provided `XOnlyPublicKey` value and returns the updated builder instance.
221    /// This is used to set the taproot public key for the program.
222    #[must_use]
223    pub fn with_taproot_pubkey(mut self, pub_key: XOnlyPublicKey) -> Self {
224        self.pub_key = pub_key;
225
226        self
227    }
228
229    /// Builds this program in the mode the protocol declares.
230    #[must_use]
231    pub fn with_debug_symbols(mut self, include: bool) -> Self {
232        self.include_debug_symbols = Some(include);
233        // This changes the output CMR, so we need to update the cache
234        self.compiled = Arc::new(OnceLock::new());
235
236        self
237    }
238
239    /// Sets storage capacity for further usage.
240    #[must_use]
241    pub fn with_storage_capacity(mut self, capacity: usize) -> Self {
242        self.storage = vec![vec![0u8; 32]; capacity];
243
244        self
245    }
246
247    /// Sets a 32-byte value at the specified index in the storage.
248    ///
249    /// # Panics
250    /// Panics if the `index` is out of bounds for the initialized storage, or if the value is not
251    /// `STORAGE_SLOT_BYTES` wide.
252    pub fn set_storage_at(&mut self, index: usize, new_value: impl Into<Vec<u8>>) {
253        let value = new_value.into();
254
255        assert!(
256            value.len() == Self::STORAGE_SLOT_BYTES,
257            "A storage slot is {} bytes, and this one is {}",
258            Self::STORAGE_SLOT_BYTES,
259            value.len()
260        );
261
262        let slot = self.storage.get_mut(index).expect("Index out of bounds");
263
264        *slot = value;
265    }
266
267    /// Returns the number of storage chunks for a program.
268    #[must_use]
269    pub fn get_storage_len(&self) -> usize {
270        self.storage.len()
271    }
272
273    /// Returns storage as a whole array of 32-byte chunks.
274    #[must_use]
275    pub fn get_storage(&self) -> &[Vec<u8>] {
276        &self.storage
277    }
278
279    /// Returns storage value at a certain index.
280    ///
281    /// # Panics
282    /// Panics if the `index` is out of bounds for the initiated storage.
283    #[must_use]
284    pub fn get_storage_at(&self, index: usize) -> Vec<u8> {
285        self.storage[index].clone()
286    }
287
288    /// Returns a taproot address for a defined `SimplicityNetwork`.
289    ///
290    /// # Panics
291    /// Panics if generating the taproot spending information fails.
292    #[must_use]
293    pub fn get_tr_address(&self, network: &SimplicityNetwork) -> Address {
294        let spend_info = self.taproot_spending_info().unwrap();
295
296        Address::p2tr(
297            secp256k1::SECP256K1,
298            spend_info.internal_key(),
299            spend_info.merkle_root(),
300            None,
301            network.address_params(),
302        )
303    }
304
305    /// Retrieves the `ScriptPubKey` associated with the Simplicity address for the specified network.
306    #[must_use]
307    pub fn get_script_pubkey(&self, network: &SimplicityNetwork) -> Script {
308        self.get_tr_address(network).script_pubkey()
309    }
310
311    /// Retrieves the 32-byte `ScriptPubKey` hash associated with the Simplicity address for the specified network.
312    #[must_use]
313    pub fn get_script_hash(&self, network: &SimplicityNetwork) -> [u8; 32] {
314        hash_script(&self.get_script_pubkey(network))
315    }
316
317    /// Compiles the program and returns its Commitment Merkle Root.
318    ///
319    /// # Panics
320    /// Panics if the `SimplicityHL` compilation fails.
321    #[must_use]
322    pub fn get_cmr(&self) -> [u8; 32] {
323        self.load().unwrap().commit().cmr().to_byte_array()
324    }
325
326    /// Returns the 32-byte tapleaf hash of the program's Simplicity script.
327    ///
328    /// # Panics
329    /// Panics if the `SimplicityHL` compilation fails.
330    #[must_use]
331    pub fn get_tapleaf_hash(&self) -> [u8; 32] {
332        let (script, version) = self.script_version().unwrap();
333
334        taproot::TapLeafHash::from_script(&script, version).to_byte_array()
335    }
336
337    /// Retrieves program ABI metadata for argument types.
338    ///
339    /// # Errors
340    /// Returns a `ProgramError` if compilation fails or generating ABI metadata fails.
341    pub fn get_argument_types(&self) -> Result<Parameters, ProgramError> {
342        let abi_meta = self
343            .load()?
344            .generate_abi_meta()
345            .map_err(ProgramError::ProgramGenAbiMeta)?;
346
347        Ok(abi_meta.param_types)
348    }
349
350    /// Retrieves the witness types from the compiled program's ABI metadata.
351    ///
352    /// # Errors
353    /// Returns a `ProgramError` if compilation fails or generating ABI metadata fails.
354    pub fn get_witness_types(&self) -> Result<WitnessTypes, ProgramError> {
355        let abi_meta = self
356            .load()?
357            .generate_abi_meta()
358            .map_err(ProgramError::ProgramGenAbiMeta)?;
359
360        Ok(abi_meta.witness_types)
361    }
362
363    fn load(&self) -> Result<&CompiledProgram, ProgramError> {
364        // Check cache first
365        if let Some(compiled) = self.compiled.get() {
366            return Ok(compiled);
367        }
368
369        let compiled = CompiledProgram::new_with_unstable(
370            Arc::clone(&self.source),
371            &UnstableFeatures::all(),
372            self.arguments.clone(),
373            self.include_debug_symbols
374                .unwrap_or_else(GlobalConfig::get_include_debug_symbols),
375            Box::new(ElementsJetHinter),
376        )
377        .map_err(ProgramError::Compilation)?;
378
379        // Update the cache
380        Ok(self.compiled.get_or_init(|| compiled))
381    }
382
383    fn script_version(&self) -> Result<(Script, taproot::LeafVersion), ProgramError> {
384        let cmr = self.load()?.commit().cmr();
385        let script = Script::from(cmr.as_ref().to_vec());
386
387        Ok((script, leaf_version()))
388    }
389
390    /// Depths of a left-folded tap tree, in the order `TaprootBuilder` wants them.
391    ///
392    /// The tree is `tapbranch(tapbranch(tapbranch(cmr, e1), e2), e3)`: the program's own leaf
393    /// and the first extra leaf sit deepest, and each further leaf is one level shallower.
394    fn taproot_leaf_depths(total_leaves: usize) -> Vec<usize> {
395        assert!(total_leaves > 0, "Taproot tree must contain at least one leaf");
396
397        let extra = total_leaves - 1;
398        let mut depths = Vec::with_capacity(total_leaves);
399
400        depths.push(extra);
401        depths.extend((1..=extra).rev());
402
403        depths
404    }
405
406    fn taproot_spending_info(&self) -> Result<taproot::TaprootSpendInfo, ProgramError> {
407        let mut builder = taproot::TaprootBuilder::new();
408        let (script, version) = self.script_version()?;
409        let depths = Self::taproot_leaf_depths(1 + self.get_storage_len());
410
411        builder = builder
412            .add_leaf_with_ver(depths[0], script, version)
413            .expect("tap tree should be valid");
414
415        for (slot, depth) in self.get_storage().iter().zip(depths.into_iter().skip(1)) {
416            builder = builder
417                .add_hidden(depth, tap_data_hash(slot))
418                .expect("tap tree should be valid");
419        }
420
421        Ok(builder
422            .finalize(secp256k1::SECP256K1, self.pub_key)
423            .expect("tap tree should be valid"))
424    }
425
426    fn control_block(&self) -> Result<taproot::ControlBlock, ProgramError> {
427        let info = self.taproot_spending_info()?;
428        let script_ver = self.script_version()?;
429
430        Ok(info.control_block(&script_ver).expect("control block should exist"))
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use simplicityhl::{
437        Arguments,
438        elements::{AssetId, confidential, pset::Input},
439    };
440
441    use super::*;
442
443    // simplicityhl/examples/cat.simf
444    const DUMMY_PROGRAM: &str = r"
445        fn main() {
446            let ab: u16 = <(u8, u8)>::into((0x10, 0x01));
447            let c: u16 = 0x1001;
448            assert!(jet::eq_16(ab, c));
449            let ab: u8 = <(u4, u4)>::into((0b1011, 0b1101));
450            let c: u8 = 0b10111101;
451            assert!(jet::eq_8(ab, c));
452        }
453    ";
454
455    fn stateful(slots: usize) -> Program {
456        Program::new(Arc::<str>::from(DUMMY_PROGRAM), &EmptyArguments).with_storage_capacity(slots)
457    }
458
459    #[test]
460    fn storage_slot_takes_a_full_width_value() {
461        let mut program = stateful(1);
462
463        program.set_storage_at(0, vec![0x11; Program::STORAGE_SLOT_BYTES]);
464
465        assert_eq!(program.get_storage_at(0), vec![0x11; Program::STORAGE_SLOT_BYTES]);
466    }
467
468    #[test]
469    #[should_panic(expected = "A storage slot is 32 bytes, and this one is 1")]
470    fn storage_slot_refuses_a_short_value() {
471        stateful(1).set_storage_at(0, vec![0x11]);
472    }
473
474    #[test]
475    #[should_panic(expected = "A storage slot is 32 bytes, and this one is 33")]
476    fn storage_slot_refuses_a_long_one() {
477        stateful(1).set_storage_at(0, vec![0x11; 33]);
478    }
479
480    #[test]
481    fn changing_a_slot_changes_the_address_but_not_the_program() {
482        let mut one = stateful(1);
483        let mut other = stateful(1);
484
485        one.set_storage_at(0, vec![0x00; Program::STORAGE_SLOT_BYTES]);
486        other.set_storage_at(0, vec![0x01; Program::STORAGE_SLOT_BYTES]);
487
488        let network = SimplicityNetwork::LiquidTestnet;
489
490        assert_ne!(one.get_tr_address(&network), other.get_tr_address(&network));
491        assert_eq!(one.get_cmr(), other.get_cmr());
492        assert_eq!(one.get_tapleaf_hash(), other.get_tapleaf_hash());
493    }
494
495    #[derive(Clone)]
496    struct EmptyArguments;
497
498    impl ArgumentsTrait for EmptyArguments {
499        fn build_arguments(&self) -> Arguments {
500            Arguments::default()
501        }
502    }
503
504    fn dummy_asset_id(byte: u8) -> AssetId {
505        AssetId::from_slice(&[byte; 32]).unwrap()
506    }
507
508    fn dummy_program() -> Program {
509        Program::new(DUMMY_PROGRAM, &EmptyArguments)
510    }
511
512    fn dummy_network() -> SimplicityNetwork {
513        SimplicityNetwork::default_regtest()
514    }
515
516    fn make_pst_with_script(script: Script) -> PartiallySignedTransaction {
517        let txout = TxOut {
518            asset: confidential::Asset::Explicit(dummy_asset_id(0xAA)),
519            value: confidential::Value::Explicit(1000),
520            script_pubkey: script,
521            ..Default::default()
522        };
523        let input = Input {
524            witness_utxo: Some(txout),
525            ..Default::default()
526        };
527
528        let mut pst = PartiallySignedTransaction::new_v2();
529
530        pst.add_input(input);
531
532        pst
533    }
534
535    #[test]
536    fn compiles_once_and_keeps_it() {
537        let program = dummy_program();
538
539        let first = program.load().expect("the dummy program compiles");
540        let second = program.load().expect("the dummy program compiles");
541
542        assert!(std::ptr::eq(first, second), "the program was compiled twice");
543    }
544
545    #[test]
546    fn changed_build_mode_is_not_served_the_old_compilation() {
547        let plain = dummy_program();
548        let plain_cmr = plain.get_cmr();
549
550        let debug = dummy_program().with_debug_symbols(true);
551        let debug_cmr = debug.get_cmr();
552
553        assert_ne!(plain_cmr, debug_cmr, "the build mode did not reach the compiler");
554    }
555
556    #[test]
557    fn test_get_env_idx() {
558        let program = dummy_program();
559        let network = dummy_network();
560
561        let correct_script = program.get_script_pubkey(&network);
562        let wrong_script = Script::new();
563
564        let mut pst = make_pst_with_script(wrong_script);
565
566        let correct_txout = TxOut {
567            asset: confidential::Asset::Explicit(dummy_asset_id(0xAA)),
568            value: confidential::Value::Explicit(1000),
569            script_pubkey: correct_script,
570            ..Default::default()
571        };
572
573        pst.add_input(Input {
574            witness_utxo: Some(correct_txout),
575            ..Default::default()
576        });
577
578        // take a script with a wrong pubkey
579        assert!(matches!(
580            program.get_env(&pst, 0, &network).unwrap_err(),
581            ProgramError::ScriptPubkeyMismatch { .. }
582        ));
583
584        assert!(program.get_env(&pst, 1, &network).is_ok());
585    }
586
587    #[test]
588    fn left_folded_depths() {
589        assert_eq!(Program::taproot_leaf_depths(1), vec![0]);
590        assert_eq!(Program::taproot_leaf_depths(2), vec![1, 1]);
591        assert_eq!(Program::taproot_leaf_depths(3), vec![2, 2, 1]);
592        assert_eq!(Program::taproot_leaf_depths(4), vec![3, 3, 2, 1]);
593        assert_eq!(Program::taproot_leaf_depths(5), vec![4, 4, 3, 2, 1]);
594    }
595
596    // The measured boundary: a balanced tree agrees with a left fold up to three leaves and
597    // diverges from four. Four leaves balanced is [2, 2, 2, 2]; left-folded it is not.
598    #[test]
599    fn diverges_from_a_balanced_tree_at_four_leaves() {
600        assert_eq!(Program::taproot_leaf_depths(3), vec![2, 2, 1]);
601        assert_ne!(Program::taproot_leaf_depths(4), vec![2, 2, 2, 2]);
602    }
603}