miden-tx 0.14.6

Miden blockchain transaction executor and prover
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
use alloc::vec::Vec;

use miden_processor::ProcessorState;
use miden_processor::advice::{AdviceMutation, AdviceProvider};
use miden_processor::trace::RowIndex;
use miden_protocol::account::{
    AccountId,
    StorageMap,
    StorageMapKey,
    StorageSlotName,
    StorageSlotType,
};
use miden_protocol::asset::{Asset, AssetVault, AssetVaultKey, FungibleAsset};
use miden_protocol::note::{
    NoteAttachment,
    NoteAttachmentArray,
    NoteAttachmentContent,
    NoteAttachmentKind,
    NoteAttachmentScheme,
    NoteId,
    NoteMetadata,
    NoteRecipient,
    NoteScript,
    NoteStorage,
    NoteTag,
    NoteType,
};
use miden_protocol::transaction::memory::{NOTE_MEM_SIZE, OUTPUT_NOTE_SECTION_OFFSET};
use miden_protocol::transaction::{TransactionEventId, TransactionSummary};
use miden_protocol::vm::EventId;
use miden_protocol::{Felt, Hasher, Word};

use crate::host::{TransactionBaseHost, TransactionKernelProcess};
use crate::{LinkMap, TransactionKernelError};

// TRANSACTION PROGRESS EVENT
// ================================================================================================
#[derive(Debug)]
pub(crate) enum TransactionProgressEvent {
    PrologueStart(RowIndex),
    PrologueEnd(RowIndex),

    NotesProcessingStart(RowIndex),
    NotesProcessingEnd(RowIndex),

    NoteExecutionStart { note_id: NoteId, clk: RowIndex },
    NoteExecutionEnd(RowIndex),

    TxScriptProcessingStart(RowIndex),
    TxScriptProcessingEnd(RowIndex),

    EpilogueStart(RowIndex),
    EpilogueEnd(RowIndex),

    EpilogueAuthProcStart(RowIndex),
    EpilogueAuthProcEnd(RowIndex),

    EpilogueAfterTxCyclesObtained(RowIndex),
}

// TRANSACTION EVENT
// ================================================================================================

/// The data necessary to handle a [`TransactionEventId`].
#[derive(Debug)]
pub(crate) enum TransactionEvent {
    /// The data necessary to request a foreign account's data from the data store.
    AccountBeforeForeignLoad {
        /// The foreign account's ID.
        foreign_account_id: AccountId,
    },

    AccountVaultAfterRemoveAsset {
        asset: Asset,
    },

    AccountVaultAfterAddAsset {
        asset: Asset,
    },

    AccountStorageAfterSetItem {
        slot_name: StorageSlotName,
        new_value: Word,
    },

    AccountStorageAfterSetMapItem {
        slot_name: StorageSlotName,
        key: StorageMapKey,
        old_value: Word,
        new_value: Word,
    },

    /// The data necessary to request a storage map witness from the data store.
    AccountStorageBeforeMapItemAccess {
        /// The account ID for whose storage a witness is requested.
        active_account_id: AccountId,
        /// The root of the storage map for which a witness is requested.
        map_root: Word,
        /// The raw map key for which a witness is requested.
        map_key: StorageMapKey,
    },

    /// The data necessary to request an asset witness from the data store.
    AccountVaultBeforeAssetAccess {
        /// The account ID for whose vault a witness is requested.
        active_account_id: AccountId,
        /// The vault root identifying the asset vault from which a witness is requested.
        vault_root: Word,
        /// The asset for which a witness is requested.
        asset_key: AssetVaultKey,
    },

    AccountAfterIncrementNonce,

    AccountPushProcedureIndex {
        /// The code commitment of the active account.
        code_commitment: Word,
        /// The procedure root whose index is requested.
        procedure_root: Word,
    },

    NoteBeforeCreated {
        /// The note index extracted from the stack.
        note_idx: usize,
        /// The note metadata extracted from the stack.
        metadata: NoteMetadata,
        /// The recipient data extracted from the advice inputs.
        recipient_data: RecipientData,
    },

    NoteBeforeAddAsset {
        /// The note index to which the asset is added.
        note_idx: usize,
        /// The asset that is added to the output note.
        asset: Asset,
    },

    NoteBeforeSetAttachment {
        /// The note index on which the attachment is set.
        note_idx: usize,
        /// The attachment that is set.
        attachment: NoteAttachment,
    },

    /// The data necessary to handle an auth request.
    AuthRequest {
        pub_key_hash: Word,
        tx_summary: TransactionSummary,
        signature: Option<Vec<Felt>>,
    },

    Unauthorized {
        tx_summary: TransactionSummary,
    },

    EpilogueBeforeTxFeeRemovedFromAccount {
        fee_asset: FungibleAsset,
    },

    LinkMapSet {
        advice_mutation: Vec<AdviceMutation>,
    },
    LinkMapGet {
        advice_mutation: Vec<AdviceMutation>,
    },

    Progress(TransactionProgressEvent),
}

impl TransactionEvent {
    /// Extracts the [`TransactionEventId`] from the stack as well as the data necessary to handle
    /// it.
    ///
    /// Returns `Some` if the extracted [`TransactionEventId`] resulted in an event that needs to be
    /// handled, `None` otherwise.
    pub fn extract<'store, STORE>(
        base_host: &TransactionBaseHost<'store, STORE>,
        process: &ProcessorState,
    ) -> Result<Option<TransactionEvent>, TransactionKernelError> {
        let event_id = EventId::from_felt(process.get_stack_item(0));
        let tx_event_id = TransactionEventId::try_from(event_id).map_err(|err| {
            TransactionKernelError::other_with_source(
                "failed to convert event ID into transaction event ID",
                err,
            )
        })?;

        let tx_event = match tx_event_id {
            TransactionEventId::AccountBeforeForeignLoad => {
                // Expected stack state: [event, account_id_suffix, account_id_prefix]
                let account_id_suffix = process.get_stack_item(1);
                let account_id_prefix = process.get_stack_item(2);
                let account_id = AccountId::try_from_elements(account_id_suffix, account_id_prefix)
                    .map_err(|err| {
                        TransactionKernelError::other_with_source(
                            "failed to convert account ID word into account ID",
                            err,
                        )
                    })?;

                Some(TransactionEvent::AccountBeforeForeignLoad { foreign_account_id: account_id })
            },
            TransactionEventId::AccountVaultBeforeAddAsset
            | TransactionEventId::AccountVaultBeforeRemoveAsset => {
                // Expected stack state: [event, ASSET_KEY, ASSET_VALUE, account_vault_root_ptr]
                let asset_vault_key = process.get_stack_word(1);
                let vault_root_ptr = process.get_stack_item(9);

                let asset_vault_key =
                    AssetVaultKey::try_from(asset_vault_key).map_err(|source| {
                        TransactionKernelError::MalformedAssetInEventHandler {
                            handler: "AccountVaultBefore{Add,Remove}Asset",
                            source,
                        }
                    })?;
                let current_vault_root = process.get_vault_root(vault_root_ptr)?;

                on_account_vault_asset_accessed(
                    base_host,
                    process,
                    asset_vault_key,
                    current_vault_root,
                )?
            },
            TransactionEventId::AccountVaultAfterRemoveAsset => {
                // Expected stack state: [event, ASSET_KEY, ASSET_VALUE]
                let asset_key = process.get_stack_word(1);
                let asset_value = process.get_stack_word(5);

                let asset =
                    Asset::from_key_value_words(asset_key, asset_value).map_err(|source| {
                        TransactionKernelError::MalformedAssetInEventHandler {
                            handler: "AccountVaultAfterRemoveAsset",
                            source,
                        }
                    })?;

                Some(TransactionEvent::AccountVaultAfterRemoveAsset { asset })
            },
            TransactionEventId::AccountVaultAfterAddAsset => {
                // Expected stack state: [event, ASSET_KEY, ASSET_VALUE]
                let asset_key = process.get_stack_word(1);
                let asset_value = process.get_stack_word(5);

                let asset =
                    Asset::from_key_value_words(asset_key, asset_value).map_err(|source| {
                        TransactionKernelError::MalformedAssetInEventHandler {
                            handler: "AccountVaultAfterAddAsset",
                            source,
                        }
                    })?;

                Some(TransactionEvent::AccountVaultAfterAddAsset { asset })
            },
            TransactionEventId::AccountVaultBeforeGetAsset => {
                // Expected stack state:
                // [event, ASSET_KEY, vault_root_ptr]
                let asset_key = process.get_stack_word(1);
                let vault_root_ptr = process.get_stack_item(5);

                let asset_key = AssetVaultKey::try_from(asset_key).map_err(|source| {
                    TransactionKernelError::MalformedAssetInEventHandler {
                        handler: "AccountVaultBeforeGetAsset",
                        source,
                    }
                })?;
                let vault_root = process.get_vault_root(vault_root_ptr)?;

                on_account_vault_asset_accessed(base_host, process, asset_key, vault_root)?
            },

            TransactionEventId::AccountStorageBeforeSetItem => None,

            TransactionEventId::AccountStorageAfterSetItem => {
                // Expected stack state: [event, slot_ptr, VALUE]
                let slot_ptr = process.get_stack_item(1);
                let new_value = process.get_stack_word(2);

                let (slot_id, slot_type, _old_value) = process.get_storage_slot(slot_ptr)?;

                let slot_header = base_host.initial_account_storage_slot(slot_id)?;
                let slot_name = slot_header.name().clone();

                if !slot_type.is_value() {
                    return Err(TransactionKernelError::other(format!(
                        "expected slot to be of type value, found {slot_type}"
                    )));
                }

                Some(TransactionEvent::AccountStorageAfterSetItem { slot_name, new_value })
            },

            TransactionEventId::AccountStorageBeforeGetMapItem => {
                // Expected stack state: [event, slot_ptr, KEY]
                let slot_ptr = process.get_stack_item(1);
                let map_key = process.get_stack_word(2);
                let map_key = StorageMapKey::from_raw(map_key);

                on_account_storage_map_item_accessed(base_host, process, slot_ptr, map_key)?
            },

            TransactionEventId::AccountStorageBeforeSetMapItem => {
                // Expected stack state: [event, slot_ptr, KEY]
                let slot_ptr = process.get_stack_item(1);
                let map_key = process.get_stack_word(2);
                let map_key = StorageMapKey::from_raw(map_key);

                on_account_storage_map_item_accessed(base_host, process, slot_ptr, map_key)?
            },

            TransactionEventId::AccountStorageAfterSetMapItem => {
                // Expected stack state: [event, slot_ptr, KEY, OLD_VALUE, NEW_VALUE]
                let slot_ptr = process.get_stack_item(1);
                let key = process.get_stack_word(2);
                let old_value = process.get_stack_word(6);
                let new_value = process.get_stack_word(10);

                let key = StorageMapKey::from_raw(key);
                // Resolve slot ID to slot name.
                let (slot_id, ..) = process.get_storage_slot(slot_ptr)?;
                let slot_header = base_host.initial_account_storage_slot(slot_id)?;
                let slot_name = slot_header.name().clone();

                Some(TransactionEvent::AccountStorageAfterSetMapItem {
                    slot_name,
                    key,
                    old_value,
                    new_value,
                })
            },

            TransactionEventId::AccountBeforeIncrementNonce => None,

            TransactionEventId::AccountAfterIncrementNonce => {
                Some(TransactionEvent::AccountAfterIncrementNonce)
            },

            TransactionEventId::AccountPushProcedureIndex => {
                // Expected stack state: [event, PROC_ROOT]
                let procedure_root = process.get_stack_word(1);
                let code_commitment = process.get_active_account_code_commitment()?;

                Some(TransactionEvent::AccountPushProcedureIndex {
                    code_commitment,
                    procedure_root,
                })
            },

            TransactionEventId::NoteBeforeCreated => {
                // Expected stack state:  [event, tag, note_type, RECIPIENT]
                let tag = process.get_stack_item(1);
                let note_type = process.get_stack_item(2);
                let recipient_digest = process.get_stack_word(3);

                let sender = base_host.native_account_id();
                let metadata = build_note_metadata(sender, note_type, tag)?;

                let note_idx = process.get_num_output_notes() as usize;

                // try to read the full recipient from the advice provider
                let recipient_data = if process.has_advice_map_entry(recipient_digest) {
                    let (note_storage, script_root, serial_num) =
                        process.read_note_recipient_info_from_adv_map(recipient_digest)?;

                    let note_script = process
                        .advice_provider()
                        .get_mapped_values(&script_root)
                        .map(|script_data| {
                            NoteScript::try_from(script_data).map_err(|source| {
                                TransactionKernelError::MalformedNoteScript {
                                    data: script_data.to_vec(),
                                    source,
                                }
                            })
                        })
                        .transpose()?;

                    match note_script {
                        Some(note_script) => {
                            let recipient =
                                NoteRecipient::new(serial_num, note_script, note_storage);

                            if recipient.digest() != recipient_digest {
                                return Err(TransactionKernelError::other(format!(
                                    "recipient digest is {recipient_digest}, but recipient constructed from raw inputs has digest {}",
                                    recipient.digest()
                                )));
                            }

                            RecipientData::Recipient(recipient)
                        },
                        None => RecipientData::ScriptMissing {
                            recipient_digest,
                            serial_num,
                            script_root,
                            note_storage,
                        },
                    }
                } else {
                    RecipientData::Digest(recipient_digest)
                };

                Some(TransactionEvent::NoteBeforeCreated { note_idx, metadata, recipient_data })
            },

            TransactionEventId::NoteAfterCreated => None,

            TransactionEventId::NoteBeforeAddAsset => {
                // Expected stack state: [event, ASSET_KEY, ASSET_VALUE, note_idx]
                let asset_key = process.get_stack_word(1);
                let asset_value = process.get_stack_word(5);
                let note_idx = process.get_stack_item(9);

                let asset =
                    Asset::from_key_value_words(asset_key, asset_value).map_err(|source| {
                        TransactionKernelError::MalformedAssetInEventHandler {
                            handler: "NoteBeforeAddAsset",
                            source,
                        }
                    })?;
                let note_idx = note_idx.as_canonical_u64() as usize;

                Some(TransactionEvent::NoteBeforeAddAsset { note_idx, asset })
            },

            TransactionEventId::NoteAfterAddAsset => None,

            TransactionEventId::NoteBeforeSetAttachment => {
                // Expected stack state: [
                //     event, attachment_scheme, attachment_kind,
                //     note_ptr, note_ptr, ATTACHMENT
                // ]

                let attachment_scheme = process.get_stack_item(1);
                let attachment_kind = process.get_stack_item(2);
                let note_ptr = process.get_stack_item(3);
                let attachment = process.get_stack_word(5);

                let (note_idx, attachment) = extract_note_attachment(
                    attachment_scheme,
                    attachment_kind,
                    attachment,
                    note_ptr,
                    process.advice_provider(),
                )?;

                Some(TransactionEvent::NoteBeforeSetAttachment { note_idx, attachment })
            },

            TransactionEventId::AuthRequest => {
                // Expected stack state: [event, MESSAGE, PUB_KEY]
                let message = process.get_stack_word(1);
                let pub_key_hash = process.get_stack_word(5);
                let signature_key = Hasher::merge(&[pub_key_hash, message]);

                let signature = process
                    .advice_provider()
                    .get_mapped_values(&signature_key)
                    .map(|slice| slice.to_vec());

                let tx_summary = extract_tx_summary(base_host, process, message)?;

                Some(TransactionEvent::AuthRequest { pub_key_hash, tx_summary, signature })
            },

            TransactionEventId::Unauthorized => {
                // Expected stack state: [event, MESSAGE]
                let message = process.get_stack_word(1);
                let tx_summary = extract_tx_summary(base_host, process, message)?;

                Some(TransactionEvent::Unauthorized { tx_summary })
            },

            TransactionEventId::EpilogueBeforeTxFeeRemovedFromAccount => {
                // Expected stack state: [event, FEE_ASSET_KEY, FEE_ASSET_VALUE]
                let fee_asset_key = process.get_stack_word(1);
                let fee_asset_value = process.get_stack_word(5);

                let fee_asset = FungibleAsset::from_key_value_words(fee_asset_key, fee_asset_value)
                    .map_err(TransactionKernelError::FailedToConvertFeeAsset)?;

                Some(TransactionEvent::EpilogueBeforeTxFeeRemovedFromAccount { fee_asset })
            },

            TransactionEventId::LinkMapSet => Some(TransactionEvent::LinkMapSet {
                advice_mutation: LinkMap::handle_set_event(process),
            }),
            TransactionEventId::LinkMapGet => Some(TransactionEvent::LinkMapGet {
                advice_mutation: LinkMap::handle_get_event(process),
            }),

            TransactionEventId::PrologueStart => Some(TransactionEvent::Progress(
                TransactionProgressEvent::PrologueStart(process.clock()),
            )),
            TransactionEventId::PrologueEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::PrologueEnd(process.clock()),
            )),

            TransactionEventId::NotesProcessingStart => Some(TransactionEvent::Progress(
                TransactionProgressEvent::NotesProcessingStart(process.clock()),
            )),
            TransactionEventId::NotesProcessingEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::NotesProcessingEnd(process.clock()),
            )),

            TransactionEventId::NoteExecutionStart => {
                let note_id = process.get_active_note_id()?.ok_or_else(|| TransactionKernelError::other(
                    "note execution interval measurement is incorrect: check the placement of the start and the end of the interval",
                ))?;

                Some(TransactionEvent::Progress(TransactionProgressEvent::NoteExecutionStart {
                    note_id,
                    clk: process.clock(),
                }))
            },
            TransactionEventId::NoteExecutionEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::NoteExecutionEnd(process.clock()),
            )),

            TransactionEventId::TxScriptProcessingStart => Some(TransactionEvent::Progress(
                TransactionProgressEvent::TxScriptProcessingStart(process.clock()),
            )),
            TransactionEventId::TxScriptProcessingEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::TxScriptProcessingEnd(process.clock()),
            )),

            TransactionEventId::EpilogueStart => Some(TransactionEvent::Progress(
                TransactionProgressEvent::EpilogueStart(process.clock()),
            )),
            TransactionEventId::EpilogueEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::EpilogueEnd(process.clock()),
            )),

            TransactionEventId::EpilogueAuthProcStart => Some(TransactionEvent::Progress(
                TransactionProgressEvent::EpilogueAuthProcStart(process.clock()),
            )),
            TransactionEventId::EpilogueAuthProcEnd => Some(TransactionEvent::Progress(
                TransactionProgressEvent::EpilogueAuthProcEnd(process.clock()),
            )),

            TransactionEventId::EpilogueAfterTxCyclesObtained => Some(TransactionEvent::Progress(
                TransactionProgressEvent::EpilogueAfterTxCyclesObtained(process.clock()),
            )),
        };

        Ok(tx_event)
    }
}

// RECIPIENT DATA
// ================================================================================================

/// The partial data to construct a note recipient.
#[derive(Debug)]
pub(crate) enum RecipientData {
    /// Only the recipient digest is available.
    Digest(Word),
    /// The full [`NoteRecipient`] is available.
    Recipient(NoteRecipient),
    /// Everything but the note script is available.
    ScriptMissing {
        recipient_digest: Word,
        serial_num: Word,
        script_root: Word,
        note_storage: NoteStorage,
    },
}

/// Checks if the necessary witness for accessing the asset identified by the vault key is already
/// in the merkle store, and:
/// - If so, returns `None`.
/// - If not, returns `Some` with all necessary data for requesting it.
fn on_account_vault_asset_accessed<'store, STORE>(
    base_host: &TransactionBaseHost<'store, STORE>,
    process: &ProcessorState,
    vault_key: AssetVaultKey,
    vault_root: Word,
) -> Result<Option<TransactionEvent>, TransactionKernelError> {
    let leaf_index = Felt::try_from(vault_key.to_leaf_index().position())
        .expect("expected key index to be a felt");
    let active_account_id = process.get_active_account_id()?;

    // For the native account we need to explicitly request the initial vault root, while for
    // foreign accounts the current vault root is always the initial one.
    let vault_root = if active_account_id == base_host.native_account_id() {
        base_host.initial_account_header().vault_root()
    } else {
        vault_root
    };

    // Note that we check whether a merkle path for the current vault root is present, not
    // necessarily for the root we are going to request. This is because the end goal is to
    // enable access to an asset against the current vault root, and so if this
    // condition is already satisfied, there is nothing to request.
    if process.has_merkle_path::<{ AssetVault::DEPTH }>(vault_root, leaf_index)? {
        // If the witness already exists, the event does not need to be handled.
        Ok(None)
    } else {
        Ok(Some(TransactionEvent::AccountVaultBeforeAssetAccess {
            active_account_id,
            vault_root,
            asset_key: vault_key,
        }))
    }
}

/// Checks if the necessary witness for accessing the map item identified by the map key is already
/// in the merkle store, and:
/// - If so, returns `None`.
/// - If not, returns `Some` with all necessary data for requesting it.
fn on_account_storage_map_item_accessed<'store, STORE>(
    base_host: &TransactionBaseHost<'store, STORE>,
    process: &ProcessorState,
    slot_ptr: Felt,
    map_key: StorageMapKey,
) -> Result<Option<TransactionEvent>, TransactionKernelError> {
    let (slot_id, slot_type, current_map_root) = process.get_storage_slot(slot_ptr)?;

    if !slot_type.is_map() {
        return Err(TransactionKernelError::other(format!(
            "expected slot to be of type map, found {slot_type}"
        )));
    }

    let active_account_id = process.get_active_account_id()?;
    let leaf_index: Felt = map_key
        .hash()
        .to_leaf_index()
        .position()
        .try_into()
        .expect("expected key index to be a felt");

    // For the native account we need to explicitly request the initial map root,
    // while for foreign accounts the current map root is always the initial one.
    let map_root = if active_account_id == base_host.native_account_id() {
        // For native accounts, we have to request witnesses against the initial
        // root instead of the _current_ one, since the data
        // store only has witnesses for initial one.
        let slot_header = base_host.initial_account_storage_slot(slot_id)?;

        if slot_header.slot_type() != StorageSlotType::Map {
            return Err(TransactionKernelError::other(format!(
                "expected slot {slot_id} to be of type map"
            )));
        }
        slot_header.value()
    } else {
        current_map_root
    };

    if process.has_merkle_path::<{ StorageMap::DEPTH }>(current_map_root, leaf_index)? {
        // If the witness already exists, the event does not need to be handled.
        Ok(None)
    } else {
        Ok(Some(TransactionEvent::AccountStorageBeforeMapItemAccess {
            active_account_id,
            map_root,
            map_key,
        }))
    }
}

/// Extracts the transaction summary from the advice map using the provided `message` as the
/// key.
///
/// ```text
/// Expected advice map state: {
///     MESSAGE: [
///         SALT, OUTPUT_NOTES_COMMITMENT, INPUT_NOTES_COMMITMENT, ACCOUNT_DELTA_COMMITMENT
///     ]
/// }
/// ```
fn extract_tx_summary<'store, STORE>(
    base_host: &TransactionBaseHost<'store, STORE>,
    process: &ProcessorState,
    message: Word,
) -> Result<TransactionSummary, TransactionKernelError> {
    let Some(commitments) = process.advice_provider().get_mapped_values(&message) else {
        return Err(TransactionKernelError::TransactionSummaryConstructionFailed(
            "expected message to exist in advice provider".into(),
        ));
    };

    if commitments.len() != 16 {
        return Err(TransactionKernelError::TransactionSummaryConstructionFailed(
            "expected 4 words for transaction summary commitments".into(),
        ));
    }

    let account_delta_commitment = extract_word(commitments, 0);
    let input_notes_commitment = extract_word(commitments, 4);
    let output_notes_commitment = extract_word(commitments, 8);
    let salt = extract_word(commitments, 12);

    let tx_summary = base_host.build_tx_summary(
        account_delta_commitment,
        input_notes_commitment,
        output_notes_commitment,
        salt,
    )?;

    if tx_summary.to_commitment() != message {
        return Err(TransactionKernelError::TransactionSummaryConstructionFailed(
            "transaction summary doesn't commit to the expected message".into(),
        ));
    }

    Ok(tx_summary)
}

// HELPER FUNCTIONS
// ================================================================================================

/// Builds the note metadata from sender, note type and tag if all inputs are valid.
fn build_note_metadata(
    sender: AccountId,
    note_type: Felt,
    tag: Felt,
) -> Result<NoteMetadata, TransactionKernelError> {
    let note_type = u8::try_from(note_type.as_canonical_u64())
        .map_err(|_| TransactionKernelError::other("failed to decode note_type into u8"))
        .and_then(|note_type_byte| {
            NoteType::try_from(note_type_byte).map_err(|source| {
                TransactionKernelError::other_with_source(
                    "failed to decode note_type from u8",
                    source,
                )
            })
        })?;

    let tag = u32::try_from(tag.as_canonical_u64())
        .map_err(|_| TransactionKernelError::other("failed to decode note tag into u32"))
        .map(NoteTag::new)?;

    Ok(NoteMetadata::new(sender, note_type).with_tag(tag))
}

fn extract_note_attachment(
    attachment_scheme: Felt,
    attachment_kind: Felt,
    attachment: Word,
    note_ptr: Felt,
    advice_provider: &AdviceProvider,
) -> Result<(usize, NoteAttachment), TransactionKernelError> {
    let note_idx = note_ptr_to_idx(note_ptr)?;

    let attachment_kind = u8::try_from(attachment_kind.as_canonical_u64())
        .map_err(|_| TransactionKernelError::other("failed to convert attachment kind to u8"))
        .and_then(|attachment_kind| {
            NoteAttachmentKind::try_from(attachment_kind).map_err(|source| {
                TransactionKernelError::other_with_source(
                    "failed to convert u8 to attachment kind",
                    source,
                )
            })
        })?;

    let attachment_scheme = u32::try_from(attachment_scheme.as_canonical_u64())
        .map_err(|_| TransactionKernelError::other("failed to convert attachment scheme to u32"))
        .map(NoteAttachmentScheme::new)?;

    let attachment_content = match attachment_kind {
        NoteAttachmentKind::None => {
            if !attachment.is_empty() {
                return Err(TransactionKernelError::NoteAttachmentNoneIsNotEmpty);
            }
            NoteAttachmentContent::None
        },
        NoteAttachmentKind::Word => NoteAttachmentContent::Word(attachment),
        NoteAttachmentKind::Array => {
            let elements = advice_provider.get_mapped_values(&attachment).ok_or_else(|| {
              TransactionKernelError::other(
                  "elements of a note attachment commitment must be present in the advice provider",
              )
            })?;

            let commitment_attachment =
                NoteAttachmentArray::new(elements.to_vec()).map_err(|source| {
                    TransactionKernelError::other_with_source(
                        "failed to construct note attachment commitment",
                        source,
                    )
                })?;

            if commitment_attachment.commitment() != attachment {
                return Err(TransactionKernelError::NoteAttachmentArrayMismatch {
                    actual: commitment_attachment.commitment(),
                    provided: attachment,
                });
            }

            NoteAttachmentContent::Array(commitment_attachment)
        },
    };

    let attachment =
        NoteAttachment::new(attachment_scheme, attachment_content).map_err(|source| {
            TransactionKernelError::other_with_source("failed to extract note attachment", source)
        })?;

    Ok((note_idx as usize, attachment))
}

/// Extracts a word from a slice of field elements.
#[inline(always)]
fn extract_word(commitments: &[Felt], start: usize) -> Word {
    Word::from([
        commitments[start],
        commitments[start + 1],
        commitments[start + 2],
        commitments[start + 3],
    ])
}

/// Converts the provided note ptr into the corresponding note index.
fn note_ptr_to_idx(note_ptr: Felt) -> Result<u32, TransactionKernelError> {
    u32::try_from(note_ptr.as_canonical_u64())
        .map_err(|_| TransactionKernelError::other("failed to convert note_ptr to u32"))
        .and_then(|note_ptr| {
            note_ptr
                .checked_sub(OUTPUT_NOTE_SECTION_OFFSET)
                .ok_or_else(|| {
                    TransactionKernelError::other("failed to calculate note_idx from note_ptr")
                })
                .map(|note_ptr| note_ptr / NOTE_MEM_SIZE)
        })
}