miden_testing/tx_context/
context.rs1use alloc::borrow::ToOwned;
2use alloc::collections::{BTreeMap, BTreeSet};
3use alloc::sync::Arc;
4use alloc::vec::Vec;
5
6use miden_processor::mast::MastForest;
7use miden_processor::{ExecutionOutput, FutureMaybeSend, MastForestStore, Word};
8use miden_protocol::account::{
9 Account,
10 AccountId,
11 PartialAccount,
12 StorageMapKey,
13 StorageMapWitness,
14 StorageSlotContent,
15};
16use miden_protocol::assembly::debuginfo::{SourceLanguage, Uri};
17use miden_protocol::assembly::{Assembler, SourceManager, SourceManagerSync};
18use miden_protocol::asset::{Asset, AssetCallbackFlag, AssetVaultKey, AssetWitness};
19use miden_protocol::block::account_tree::AccountWitness;
20use miden_protocol::block::{BlockHeader, BlockNumber};
21use miden_protocol::note::{Note, NoteScript, NoteScriptRoot};
22use miden_protocol::transaction::{
23 AccountInputs,
24 ExecutedTransaction,
25 InputNote,
26 InputNotes,
27 PartialBlockchain,
28 TransactionArgs,
29 TransactionInputs,
30 TransactionKernel,
31};
32use miden_standards::code_builder::CodeBuilder;
33use miden_tx::auth::{BasicAuthenticator, UnreachableAuth};
34use miden_tx::{
35 AccountProcedureIndexMap,
36 DataStore,
37 DataStoreError,
38 ScriptMastForestStore,
39 TransactionExecutor,
40 TransactionExecutorError,
41 TransactionExecutorHost,
42 TransactionMastStore,
43};
44
45use crate::executor::CodeExecutor;
46use crate::mock_host::MockHost;
47use crate::tx_context::ExecError;
48
49pub struct TransactionContext {
57 pub(super) account: Account,
58 pub(super) expected_output_notes: Vec<Note>,
59 pub(super) foreign_account_inputs: BTreeMap<AccountId, (Account, AccountWitness)>,
60 pub(super) tx_inputs: TransactionInputs,
61 pub(super) mast_store: TransactionMastStore,
62 pub(super) authenticator: Option<BasicAuthenticator>,
63 pub(super) source_manager: Arc<dyn SourceManagerSync>,
64 pub(super) note_scripts: BTreeMap<NoteScriptRoot, NoteScript>,
65 pub(super) is_lazy_loading_enabled: bool,
66 pub(super) is_debug_mode_enabled: bool,
67}
68
69impl TransactionContext {
70 pub async fn execute_code(&self, code: &str) -> Result<ExecutionOutput, ExecError> {
86 let mut asset_vault_keys = self
88 .tx_inputs
89 .input_notes()
90 .iter()
91 .flat_map(|note| note.note().assets().iter().map(Asset::vault_key))
92 .collect::<BTreeSet<_>>();
93
94 let (account, block_header, _blockchain) = self
95 .get_transaction_inputs(
96 self.tx_inputs.account().id(),
97 BTreeSet::from_iter([self.tx_inputs.block_header().block_num()]),
98 )
99 .await
100 .expect("failed to fetch transaction inputs");
101
102 let fee_asset_vault_key = AssetVaultKey::new_fungible(
105 block_header.fee_parameters().fee_faucet_id(),
106 AssetCallbackFlag::Disabled,
108 );
109 asset_vault_keys.insert(fee_asset_vault_key);
110
111 let asset_witnesses = self
113 .get_vault_asset_witnesses(account.id(), account.vault().root(), asset_vault_keys)
114 .await
115 .expect("failed to fetch asset witnesses");
116
117 let tx_inputs = self.tx_inputs.clone().with_asset_witnesses(asset_witnesses);
118 let (stack_inputs, advice_inputs) = TransactionKernel::prepare_inputs(&tx_inputs);
119
120 let virtual_source_file = self.source_manager.load(
122 SourceLanguage::Masm,
123 Uri::new("_tx_context_code"),
124 code.to_owned(),
125 );
126
127 let assembler: Assembler =
128 CodeBuilder::with_mock_libraries_with_source_manager(self.source_manager.clone())
129 .into();
130
131 let program = assembler
132 .assemble_program(virtual_source_file)
133 .expect("code was not well formed");
134
135 self.mast_store.insert(TransactionKernel::library().mast_forest().clone());
139 self.mast_store.insert(program.mast_forest().clone());
140
141 let account_procedure_idx_map = AccountProcedureIndexMap::new(
142 [tx_inputs.account().code()]
143 .into_iter()
144 .chain(self.foreign_account_inputs.values().map(|(account, _)| account.code())),
145 );
146
147 let ref_block = tx_inputs.block_header().block_num();
149
150 let exec_host = TransactionExecutorHost::<'_, '_, _, UnreachableAuth>::new(
151 &PartialAccount::from(self.account()),
152 tx_inputs.input_notes().clone(),
153 self,
154 ScriptMastForestStore::default(),
155 account_procedure_idx_map,
156 None,
157 ref_block,
158 0u64,
161 self.source_manager(),
162 );
163
164 let advice_inputs = advice_inputs.into_advice_inputs();
165
166 let mut mock_host = MockHost::new(exec_host);
167 if self.is_lazy_loading_enabled {
168 mock_host.enable_lazy_loading()
169 }
170
171 CodeExecutor::new(mock_host)
172 .stack_inputs(stack_inputs)
173 .extend_advice_inputs(advice_inputs)
174 .execute_program(program)
175 .await
176 }
177
178 pub async fn execute(self) -> Result<ExecutedTransaction, TransactionExecutorError> {
180 let account_id = self.account().id();
181 let block_num = self.tx_inputs().block_header().block_num();
182 let notes = self.tx_inputs().input_notes().clone();
183 let tx_args = self.tx_args().clone();
184
185 let mut tx_executor =
186 TransactionExecutor::new(&self).with_source_manager(self.source_manager.clone());
187
188 if self.is_debug_mode_enabled {
189 tx_executor = tx_executor.with_debug_mode();
190 }
191
192 if let Some(authenticator) = self.authenticator() {
193 tx_executor = tx_executor.with_authenticator(authenticator);
194 }
195
196 tx_executor.execute_transaction(account_id, block_num, notes, tx_args).await
197 }
198
199 pub fn account(&self) -> &Account {
200 &self.account
201 }
202
203 pub fn expected_output_notes(&self) -> &[Note] {
204 &self.expected_output_notes
205 }
206
207 pub fn tx_args(&self) -> &TransactionArgs {
208 self.tx_inputs.tx_args()
209 }
210
211 pub fn input_notes(&self) -> &InputNotes<InputNote> {
212 self.tx_inputs.input_notes()
213 }
214
215 pub fn set_tx_args(&mut self, tx_args: TransactionArgs) {
216 self.tx_inputs.set_tx_args(tx_args);
217 }
218
219 pub fn tx_inputs(&self) -> &TransactionInputs {
220 &self.tx_inputs
221 }
222
223 pub fn authenticator(&self) -> Option<&BasicAuthenticator> {
224 self.authenticator.as_ref()
225 }
226
227 pub fn source_manager(&self) -> Arc<dyn SourceManagerSync> {
229 Arc::clone(&self.source_manager)
230 }
231}
232
233impl DataStore for TransactionContext {
234 fn get_transaction_inputs(
235 &self,
236 account_id: AccountId,
237 ref_blocks: BTreeSet<BlockNumber>,
238 ) -> impl FutureMaybeSend<Result<(PartialAccount, BlockHeader, PartialBlockchain), DataStoreError>>
239 {
240 assert_eq!(account_id, self.account().id());
242 assert_eq!(account_id, self.tx_inputs.account().id());
243 assert_eq!(
244 ref_blocks
245 .last()
246 .copied()
247 .expect("at least the tx ref block should be provided"),
248 self.tx_inputs().blockchain().chain_length(),
249 "tx reference block should match partial blockchain length"
250 );
251
252 let account = self.tx_inputs.account().clone();
253 let block_header = self.tx_inputs.block_header().clone();
254 let blockchain = self.tx_inputs.blockchain().clone();
255
256 async move { Ok((account, block_header, blockchain)) }
257 }
258
259 fn get_foreign_account_inputs(
260 &self,
261 foreign_account_id: AccountId,
262 _ref_block: BlockNumber,
263 ) -> impl FutureMaybeSend<Result<AccountInputs, DataStoreError>> {
264 async move {
267 let (foreign_account, account_witness) =
268 self.foreign_account_inputs.get(&foreign_account_id).ok_or_else(|| {
269 DataStoreError::other(format!(
270 "failed to find foreign account {foreign_account_id}"
271 ))
272 })?;
273
274 Ok(AccountInputs::new(
275 PartialAccount::from(foreign_account),
276 account_witness.clone(),
277 ))
278 }
279 }
280
281 fn get_vault_asset_witnesses(
282 &self,
283 account_id: AccountId,
284 vault_root: Word,
285 vault_keys: BTreeSet<AssetVaultKey>,
286 ) -> impl FutureMaybeSend<Result<Vec<AssetWitness>, DataStoreError>> {
287 async move {
288 let asset_vault = if account_id == self.account().id() {
289 if self.account().vault().root() != vault_root {
290 return Err(DataStoreError::other(format!(
291 "native account {account_id} has vault root {} but {vault_root} was requested",
292 self.account().vault().root()
293 )));
294 }
295 self.account().vault()
296 } else {
297 let (foreign_account, _witness) = self
298 .foreign_account_inputs
299 .iter()
300 .find_map(
301 |(id, account_inputs)| {
302 if account_id == *id { Some(account_inputs) } else { None }
303 },
304 )
305 .ok_or_else(|| {
306 DataStoreError::other(format!(
307 "failed to find foreign account {account_id} in foreign account inputs"
308 ))
309 })?;
310
311 if foreign_account.vault().root() != vault_root {
312 return Err(DataStoreError::other(format!(
313 "foreign account {account_id} has vault root {} but {vault_root} was requested",
314 foreign_account.vault().root()
315 )));
316 }
317 foreign_account.vault()
318 };
319
320 Ok(vault_keys.into_iter().map(|vault_key| asset_vault.open(vault_key)).collect())
321 }
322 }
323
324 fn get_storage_map_witness(
325 &self,
326 account_id: AccountId,
327 map_root: Word,
328 map_key: StorageMapKey,
329 ) -> impl FutureMaybeSend<Result<StorageMapWitness, DataStoreError>> {
330 async move {
331 if account_id == self.account().id() {
332 let storage_map = self
334 .account()
335 .storage()
336 .slots()
337 .iter()
338 .find_map(|slot| match slot.content() {
339 StorageSlotContent::Map(storage_map) if storage_map.root() == map_root => {
340 Some(storage_map)
341 },
342 _ => None,
343 })
344 .ok_or_else(|| {
345 DataStoreError::other(format!(
346 "failed to find storage map with root {map_root} in account storage"
347 ))
348 })?;
349
350 Ok(storage_map.open(&map_key))
351 } else {
352 let (foreign_account, _witness) = self
353 .foreign_account_inputs
354 .iter()
355 .find_map(
356 |(id, account_inputs)| {
357 if account_id == *id { Some(account_inputs) } else { None }
358 },
359 )
360 .ok_or_else(|| {
361 DataStoreError::other(format!(
362 "failed to find foreign account {account_id} in foreign account inputs"
363 ))
364 })?;
365
366 let map = foreign_account
367 .storage()
368 .slots()
369 .iter()
370 .find_map(|slot| match slot.content() {
371 StorageSlotContent::Map(storage_map) if storage_map.root() == map_root => {Some(storage_map)},
372 _ => None,
373 })
374 .ok_or_else(|| {
375 DataStoreError::other(format!(
376 "failed to find storage map with root {map_root} in foreign account {account_id}"
377 ))
378 })?;
379
380 Ok(map.open(&map_key))
381 }
382 }
383 }
384
385 fn get_note_script(
386 &self,
387 script_root: NoteScriptRoot,
388 ) -> impl FutureMaybeSend<Result<Option<NoteScript>, DataStoreError>> {
389 async move { Ok(self.note_scripts.get(&script_root).cloned()) }
390 }
391}
392
393impl MastForestStore for TransactionContext {
394 fn get(&self, procedure_hash: &Word) -> Option<Arc<MastForest>> {
395 self.mast_store.get(procedure_hash)
396 }
397}
398
399#[cfg(test)]
403mod tests {
404 use miden_standards::code_builder::CodeBuilder;
405
406 use super::*;
407 use crate::TransactionContextBuilder;
408
409 #[tokio::test]
410 async fn test_get_note_scripts() {
411 let script1_code = "@note_script\npub proc main\n push.1\nend";
413 let note_script1 = CodeBuilder::default()
414 .compile_note_script(script1_code)
415 .expect("failed to assemble note script 1");
416 let script_root1 = note_script1.root();
417
418 let script2_code = "@note_script\npub proc main\n push.2 push.3 add\nend";
419 let note_script2 = CodeBuilder::default()
420 .compile_note_script(script2_code)
421 .expect("failed to assemble note script 2");
422 let script_root2 = note_script2.root();
423
424 let tx_context = TransactionContextBuilder::with_existing_mock_account()
426 .add_note_script(note_script1.clone())
427 .add_note_script(note_script2.clone())
428 .build()
429 .expect("failed to build transaction context");
430
431 let retrieved_script1 = tx_context
433 .get_note_script(script_root1)
434 .await
435 .expect("failed to get note script 1")
436 .expect("note script 1 should exist");
437 assert_eq!(retrieved_script1, note_script1);
438
439 let retrieved_script2 = tx_context
440 .get_note_script(script_root2)
441 .await
442 .expect("failed to get note script 2")
443 .expect("note script 2 should exist");
444 assert_eq!(retrieved_script2, note_script2);
445
446 let non_existent_root = NoteScriptRoot::from_array([1, 2, 3, 4]);
448 let result = tx_context.get_note_script(non_existent_root).await;
449 assert!(matches!(result, Ok(None)));
450 }
451}