Skip to main content

miden_testing/tx_context/
mock_transaction_builder.rs

1// MOCK TRANSACTION BUILDER
2// ================================================================================================
3
4use alloc::collections::BTreeMap;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7
8use anyhow::Context;
9use miden_processor::advice::AdviceInputs;
10use miden_processor::{Felt, Word};
11use miden_protocol::EMPTY_WORD;
12use miden_protocol::account::auth::{PublicKeyCommitment, Signature};
13use miden_protocol::account::{Account, AccountId};
14use miden_protocol::assembly::DefaultSourceManager;
15use miden_protocol::assembly::debuginfo::SourceManagerSync;
16use miden_protocol::block::BlockNumber;
17use miden_protocol::block::account_tree::AccountWitness;
18use miden_protocol::note::{Note, NoteId, NoteScript, NoteScriptRoot};
19use miden_protocol::transaction::{RawOutputNote, TransactionArgs, TransactionScript};
20use miden_tx::TransactionMastStore;
21use miden_tx::auth::BasicAuthenticator;
22
23use super::TransactionContext;
24use crate::MockChain;
25use crate::mock_chain::TxContextInput;
26
27// MOCK TRANSACTION BUILDER
28// ================================================================================================
29
30/// A builder for a [`TransactionContext`] that is coupled to a concrete [`MockChain`].
31///
32/// It is the public entry point for executing a transaction against a chain and is created through
33/// [`MockChain::build_transaction`]. Contrary to [`MockChain::build_tx_context`], input notes are
34/// not passed up front but added explicitly through [`Self::authenticated_input_note`] and
35/// [`Self::unauthenticated_input_note`]. The transaction inputs are only resolved against the chain
36/// in [`Self::build`], once all input notes are known, by calling
37/// [`MockChain::get_transaction_inputs`].
38///
39/// # Examples
40///
41/// ```
42/// # use anyhow::Result;
43/// # use miden_protocol::{asset::FungibleAsset, note::NoteType};
44/// # use miden_testing::{Auth, MockChain};
45/// #
46/// # #[tokio::main(flavor = "current_thread")]
47/// # async fn main() -> Result<()> {
48/// let mut builder = MockChain::builder();
49/// let sender = builder.add_existing_mock_account(Auth::IncrNonce)?;
50/// let account = builder.add_existing_mock_account(Auth::IncrNonce)?;
51/// let note = builder.add_p2id_note(
52///     sender.id(),
53///     account.id(),
54///     &[FungibleAsset::mock(100)],
55///     NoteType::Public,
56/// )?;
57/// let chain = builder.build()?;
58///
59/// let executed = chain
60///     .build_transaction(account.id())
61///     .authenticated_input_note(note.id())
62///     .build()?
63///     .execute()
64///     .await?;
65///
66/// assert_eq!(executed.input_notes().num_notes(), 1);
67/// # Ok(())
68/// # }
69/// ```
70pub struct MockTransactionBuilder<'chain> {
71    chain: &'chain MockChain,
72    input: TxContextInput,
73    reference_block: Option<BlockNumber>,
74    authenticated_notes: Vec<NoteId>,
75    unauthenticated_notes: Vec<Note>,
76    authenticator: Option<BasicAuthenticator>,
77    advice_inputs: AdviceInputs,
78    foreign_account_inputs: BTreeMap<AccountId, (Account, AccountWitness)>,
79    expected_output_notes: Vec<Note>,
80    tx_script: Option<TransactionScript>,
81    tx_script_args: Word,
82    auth_args: Word,
83    note_args: BTreeMap<NoteId, Word>,
84    signatures: Vec<(PublicKeyCommitment, Word, Signature)>,
85    note_scripts: BTreeMap<NoteScriptRoot, NoteScript>,
86    source_manager: Option<Arc<dyn SourceManagerSync>>,
87    is_lazy_loading_enabled: bool,
88}
89
90impl<'chain> MockTransactionBuilder<'chain> {
91    /// Creates a new [`MockTransactionBuilder`] against the provided chain.
92    ///
93    /// Use [`MockChain::build_transaction`] instead of calling this directly.
94    pub(crate) fn new(chain: &'chain MockChain, input: impl Into<TxContextInput>) -> Self {
95        let input = input.into();
96        // Resolve the chain's authenticator for the account up front. The chain is borrowed
97        // immutably for the builder's lifetime, so this default cannot change before `build`; an
98        // explicit `authenticator` call may still override it.
99        let authenticator = chain.account_authenticator(input.id());
100
101        Self {
102            chain,
103            input,
104            reference_block: None,
105            authenticated_notes: Vec::new(),
106            unauthenticated_notes: Vec::new(),
107            authenticator,
108            advice_inputs: AdviceInputs::default(),
109            foreign_account_inputs: BTreeMap::new(),
110            expected_output_notes: Vec::new(),
111            tx_script: None,
112            tx_script_args: EMPTY_WORD,
113            auth_args: EMPTY_WORD,
114            note_args: BTreeMap::new(),
115            signatures: Vec::new(),
116            note_scripts: BTreeMap::new(),
117            source_manager: None,
118            is_lazy_loading_enabled: true,
119        }
120    }
121
122    /// Adds an authenticated input note that the transaction consumes.
123    ///
124    /// The note must already be committed to the chain so that its inclusion proof can be resolved
125    /// in [`Self::build`].
126    pub fn authenticated_input_note(mut self, note_id: NoteId) -> Self {
127        self.authenticated_notes.push(note_id);
128        self
129    }
130
131    /// Adds multiple authenticated input notes that the transaction consumes.
132    ///
133    /// This is the iterator equivalent of [`Self::authenticated_input_note`].
134    pub fn authenticated_input_notes(mut self, note_ids: impl IntoIterator<Item = NoteId>) -> Self {
135        self.authenticated_notes.extend(note_ids);
136        self
137    }
138
139    /// Adds an unauthenticated input note that the transaction consumes.
140    ///
141    /// Contrary to [`Self::authenticated_input_note`], the note does not need to be committed to
142    /// the chain.
143    pub fn unauthenticated_input_note(mut self, note: Note) -> Self {
144        self.unauthenticated_notes.push(note);
145        self
146    }
147
148    /// Adds multiple unauthenticated input notes that the transaction consumes.
149    ///
150    /// This is the iterator equivalent of [`Self::unauthenticated_input_note`].
151    pub fn unauthenticated_input_notes(mut self, notes: impl IntoIterator<Item = Note>) -> Self {
152        self.unauthenticated_notes.extend(notes);
153        self
154    }
155
156    /// Sets the block the transaction executes against.
157    ///
158    /// By default the transaction is built against the chain's latest block. Use this to execute
159    /// against an earlier block instead, e.g. to test block-height-dependent script logic such as
160    /// timelocks or note expiration. All input notes must have been created at or before this
161    /// block.
162    pub fn reference_block(mut self, reference_block: impl Into<BlockNumber>) -> Self {
163        self.reference_block = Some(reference_block.into());
164        self
165    }
166
167    /// Set the authenticator for the transaction (if needed).
168    pub fn authenticator(mut self, authenticator: Option<BasicAuthenticator>) -> Self {
169        self.authenticator = authenticator;
170        self
171    }
172
173    /// Extends the advice inputs with the provided [`AdviceInputs`] instance.
174    pub fn extend_advice_inputs(mut self, advice_inputs: AdviceInputs) -> Self {
175        self.advice_inputs.extend(advice_inputs);
176        self
177    }
178
179    /// Inserts a single key-value pair into the advice inputs map.
180    ///
181    /// To add multiple entries, call this repeatedly or use [`Self::extend_advice_inputs`].
182    pub fn extend_advice_map(mut self, key: Word, value: Vec<Felt>) -> Self {
183        self.advice_inputs.map.insert(key, value);
184        self
185    }
186
187    /// Sets foreign account inputs that are used by the transaction.
188    pub fn foreign_accounts(
189        mut self,
190        inputs: impl IntoIterator<Item = (Account, AccountWitness)>,
191    ) -> Self {
192        self.foreign_account_inputs.extend(
193            inputs.into_iter().map(|(account, witness)| (account.id(), (account, witness))),
194        );
195        self
196    }
197
198    /// Sets the desired transaction script.
199    pub fn tx_script(mut self, tx_script: TransactionScript) -> Self {
200        self.tx_script = Some(tx_script);
201        self
202    }
203
204    /// Sets the transaction script arguments.
205    pub fn tx_script_args(mut self, tx_script_args: Word) -> Self {
206        self.tx_script_args = tx_script_args;
207        self
208    }
209
210    /// Sets the desired auth arguments.
211    pub fn auth_args(mut self, auth_args: Word) -> Self {
212        self.auth_args = auth_args;
213        self
214    }
215
216    /// Extends the note arguments map with the provided one.
217    pub fn extend_note_args(mut self, note_args: BTreeMap<NoteId, Word>) -> Self {
218        self.note_args.extend(note_args);
219        self
220    }
221
222    /// Adds a single expected output note.
223    ///
224    /// A [`RawOutputNote::Partial`] note is ignored, since it does not carry the recipient details
225    /// required to reconstruct the note.
226    pub fn expected_output_note(mut self, output_note: RawOutputNote) -> Self {
227        if let RawOutputNote::Full(note) = output_note {
228            self.expected_output_notes.push(note);
229        }
230        self
231    }
232
233    /// Extends the expected output notes.
234    ///
235    /// This is the iterator equivalent of [`Self::expected_output_note`].
236    pub fn expected_output_notes(mut self, output_notes: Vec<RawOutputNote>) -> Self {
237        let output_notes = output_notes.into_iter().filter_map(|note| match note {
238            RawOutputNote::Full(note) => Some(note),
239            RawOutputNote::Partial(_) => None,
240        });
241        self.expected_output_notes.extend(output_notes);
242        self
243    }
244
245    /// Adds a new signature for the message and the public key.
246    pub fn add_signature(
247        mut self,
248        pub_key: PublicKeyCommitment,
249        message: Word,
250        signature: Signature,
251    ) -> Self {
252        self.signatures.push((pub_key, message, signature));
253        self
254    }
255
256    /// Adds a note script to the context for testing.
257    pub fn add_note_script(mut self, script: NoteScript) -> Self {
258        self.note_scripts.insert(script.root(), script);
259        self
260    }
261
262    /// Sets the [`SourceManagerSync`] on the [`TransactionContext`] that will be built.
263    ///
264    /// This source manager should contain the sources of all involved scripts and account code in
265    /// order to provide better error messages if an error occurs.
266    pub fn with_source_manager(mut self, source_manager: Arc<dyn SourceManagerSync>) -> Self {
267        self.source_manager = Some(source_manager);
268        self
269    }
270
271    /// Disables lazy loading.
272    ///
273    /// Only affects [`TransactionContext::execute_code`] and causes the host to _not_ handle lazy
274    /// loading events.
275    pub fn disable_lazy_loading(mut self) -> Self {
276        self.is_lazy_loading_enabled = false;
277        self
278    }
279
280    /// Builds the [`TransactionContext`].
281    ///
282    /// The configured account and input notes are resolved into [`TransactionInputs`] against the
283    /// [`Self::reference_block`] (defaulting to the chain's latest block) through
284    /// [`MockChain::get_transaction_inputs`], and the remaining configuration is assembled into the
285    /// [`TransactionContext`].
286    ///
287    /// [`TransactionInputs`]: miden_protocol::transaction::TransactionInputs
288    pub fn build(self) -> anyhow::Result<TransactionContext> {
289        let account = self.chain.resolve_tx_account(self.input)?;
290
291        let mut tx_inputs = match self.reference_block {
292            Some(reference_block) => {
293                let latest_block = self.chain.latest_block_header().block_num();
294                anyhow::ensure!(
295                    reference_block <= latest_block,
296                    "reference block {reference_block} is out of range (latest {latest_block})",
297                );
298
299                self.chain.get_transaction_inputs_at(
300                    reference_block,
301                    &account,
302                    &self.authenticated_notes,
303                    &self.unauthenticated_notes,
304                )
305            },
306            None => self.chain.get_transaction_inputs(
307                &account,
308                &self.authenticated_notes,
309                &self.unauthenticated_notes,
310            ),
311        }
312        .context("failed to resolve transaction inputs from mock chain")?;
313
314        let mut tx_args = TransactionArgs::default().with_note_args(self.note_args);
315        if let Some(tx_script) = self.tx_script {
316            tx_args = tx_args.with_tx_script_and_args(tx_script, self.tx_script_args);
317        }
318        tx_args = tx_args.with_auth_args(self.auth_args);
319        tx_args.extend_advice_inputs(self.advice_inputs);
320        tx_args.extend_output_note_recipients(&self.expected_output_notes);
321        for (public_key_commitment, message, signature) in self.signatures {
322            tx_args.add_signature(public_key_commitment, message, signature);
323        }
324        tx_inputs.set_tx_args(tx_args);
325
326        let mast_store = TransactionMastStore::new();
327        mast_store.load_account_code(tx_inputs.account().code());
328        for (account, _) in self.foreign_account_inputs.values() {
329            mast_store.insert(account.code().mast());
330        }
331
332        let source_manager =
333            self.source_manager.unwrap_or_else(|| Arc::new(DefaultSourceManager::default()));
334
335        Ok(TransactionContext {
336            account,
337            expected_output_notes: self.expected_output_notes,
338            foreign_account_inputs: self.foreign_account_inputs,
339            tx_inputs,
340            mast_store,
341            authenticator: self.authenticator,
342            source_manager,
343            note_scripts: self.note_scripts,
344            is_lazy_loading_enabled: self.is_lazy_loading_enabled,
345        })
346    }
347}