miden-testing 0.14.3

Miden protocol testing tools
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
use alloc::string::String;

use miden_protocol::account::auth::AuthScheme;
use miden_protocol::account::{Account, AccountId};
use miden_protocol::asset::{Asset, FungibleAsset, NonFungibleAsset};
use miden_protocol::crypto::rand::RandomCoin;
use miden_protocol::errors::tx_kernel::{
    ERR_NON_FUNGIBLE_ASSET_ALREADY_EXISTS,
    ERR_TX_NUMBER_OF_OUTPUT_NOTES_EXCEEDS_LIMIT,
};
use miden_protocol::note::{
    Note,
    NoteAttachment,
    NoteAttachmentScheme,
    NoteMetadata,
    NoteRecipient,
    NoteStorage,
    NoteTag,
    NoteType,
};
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_NETWORK_NON_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PRIVATE_SENDER,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_2,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE,
    ACCOUNT_ID_SENDER,
};
use miden_protocol::testing::constants::NON_FUNGIBLE_ASSET_DATA_2;
use miden_protocol::transaction::memory::{
    ASSET_SIZE,
    ASSET_VALUE_OFFSET,
    NOTE_MEM_SIZE,
    NUM_OUTPUT_NOTES_PTR,
    OUTPUT_NOTE_ASSETS_OFFSET,
    OUTPUT_NOTE_ATTACHMENT_OFFSET,
    OUTPUT_NOTE_METADATA_HEADER_OFFSET,
    OUTPUT_NOTE_NUM_ASSETS_OFFSET,
    OUTPUT_NOTE_RECIPIENT_OFFSET,
    OUTPUT_NOTE_SECTION_OFFSET,
};
use miden_protocol::transaction::{RawOutputNote, RawOutputNotes};
use miden_protocol::{Felt, Word, ZERO};
use miden_standards::code_builder::CodeBuilder;
use miden_standards::note::{
    AccountTargetNetworkNote,
    NetworkAccountTarget,
    NetworkNoteExt,
    NoteExecutionHint,
    P2idNote,
};
use miden_standards::testing::mock_account::MockAccountExt;
use miden_standards::testing::note::NoteBuilder;

use super::{TestSetup, setup_test};
use crate::kernel_tests::tx::ExecutionOutputExt;
use crate::utils::{create_public_p2any_note, create_spawn_note};
use crate::{Auth, MockChain, TransactionContextBuilder, assert_execution_error};

#[tokio::test]
async fn test_create_note() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;
    let account_id = tx_context.account().id();

    let recipient = Word::from([0, 1, 2, 3u32]);
    let tag = NoteTag::with_account_target(account_id);

    let code = format!(
        "
        use miden::protocol::output_note

        use $kernel::prologue

        begin
            exec.prologue::prepare_transaction

            push.{recipient}
            push.{PUBLIC_NOTE}
            push.{tag}

            exec.output_note::create

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        recipient = recipient,
        PUBLIC_NOTE = NoteType::Public as u8,
        tag = tag,
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_kernel_mem_element(NUM_OUTPUT_NOTES_PTR),
        Felt::from(1u32),
        "number of output notes must increment by 1",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_RECIPIENT_OFFSET),
        recipient,
        "recipient must be stored at the correct memory location",
    );

    let metadata = NoteMetadata::new(account_id, NoteType::Public).with_tag(tag);
    let expected_metadata_header = metadata.to_header_word();
    let expected_note_attachment = metadata.to_attachment_word();

    assert_eq!(
        exec_output
            .get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_METADATA_HEADER_OFFSET),
        expected_metadata_header,
        "metadata header must be stored at the correct memory location",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ATTACHMENT_OFFSET),
        expected_note_attachment,
        "attachment must be stored at the correct memory location",
    );

    assert_eq!(
        exec_output.get_stack_element(0),
        ZERO,
        "top item on the stack is the index of the output note"
    );
    Ok(())
}

#[tokio::test]
async fn test_create_note_with_invalid_tag() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let invalid_tag = Felt::new((NoteType::Public as u64) << 62);
    let valid_tag: Felt = NoteTag::default().into();

    // Test invalid tag
    assert!(tx_context.execute_code(&note_creation_script(invalid_tag)).await.is_err());

    // Test valid tag
    assert!(tx_context.execute_code(&note_creation_script(valid_tag)).await.is_ok());

    Ok(())
}

fn note_creation_script(tag: Felt) -> String {
    format!(
        "
            use miden::protocol::output_note
            use $kernel::prologue

            begin
                exec.prologue::prepare_transaction

                push.{recipient}
                push.{PUBLIC_NOTE}
                push.{tag}

                exec.output_note::create

                # clean the stack
                dropw dropw
            end
            ",
        recipient = Word::from([0, 1, 2, 3u32]),
        PUBLIC_NOTE = NoteType::Public as u8,
    )
}

#[tokio::test]
async fn test_create_note_too_many_notes() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let code = format!(
        "
        use miden::protocol::output_note
        use $kernel::constants::MAX_OUTPUT_NOTES_PER_TX
        use $kernel::memory
        use $kernel::prologue

        begin
            push.MAX_OUTPUT_NOTES_PER_TX
            exec.memory::set_num_output_notes
            exec.prologue::prepare_transaction

            push.{recipient}
            push.{PUBLIC_NOTE}
            push.{tag}

            exec.output_note::create
        end
        ",
        tag = NoteTag::new(1234 << 16 | 5678),
        recipient = Word::from([0, 1, 2, 3u32]),
        PUBLIC_NOTE = NoteType::Public as u8,
    );

    let exec_output = tx_context.execute_code(&code).await;

    assert_execution_error!(exec_output, ERR_TX_NUMBER_OF_OUTPUT_NOTES_EXCEEDS_LIMIT);
    Ok(())
}

#[tokio::test]
async fn test_get_output_notes_commitment() -> anyhow::Result<()> {
    let mut rng = RandomCoin::new(Word::from([1, 2, 3, 4u32]));
    let account = Account::mock(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE, Auth::IncrNonce);

    let asset_1 = FungibleAsset::mock(100);
    let asset_2 = FungibleAsset::mock(200);

    let input_note_1 = create_public_p2any_note(ACCOUNT_ID_PRIVATE_SENDER.try_into()?, [asset_1]);
    let input_note_2 = create_public_p2any_note(ACCOUNT_ID_PRIVATE_SENDER.try_into()?, [asset_2]);

    // create output note 1
    let output_note_1 = NoteBuilder::new(account.id(), &mut rng)
        .tag(NoteTag::with_account_target(account.id()).as_u32())
        .note_type(NoteType::Public)
        .add_assets([asset_1])
        .build()?;

    // create output note 2
    let output_note_2 = NoteBuilder::new(account.id(), &mut rng)
        .tag(NoteTag::with_custom_account_target(account.id(), 2)?.as_u32())
        .note_type(NoteType::Public)
        .add_assets([asset_2])
        .attachment(NoteAttachment::new_array(
            NoteAttachmentScheme::new(5),
            [42, 43, 44, 45, 46u32].map(Felt::from).to_vec(),
        )?)
        .build()?;

    let tx_context = TransactionContextBuilder::new(account)
        .extend_input_notes(vec![input_note_1.clone(), input_note_2.clone()])
        .extend_expected_output_notes(vec![
            RawOutputNote::Full(output_note_1.clone()),
            RawOutputNote::Full(output_note_2.clone()),
        ])
        .build()?;

    // compute expected output notes commitment
    let expected_output_notes_commitment = RawOutputNotes::new(vec![
        RawOutputNote::Full(output_note_1.clone()),
        RawOutputNote::Full(output_note_2.clone()),
    ])?
    .commitment();

    let code = format!(
        "
        use miden::core::sys

        use miden::protocol::tx
        use miden::protocol::output_note

        use $kernel::prologue

        begin
            exec.prologue::prepare_transaction
            # => []

            # create output note 1
            push.{recipient_1}
            push.{PUBLIC_NOTE}
            push.{tag_1}
            exec.output_note::create
            # => [note_idx]

            push.{ASSET_1_VALUE}
            push.{ASSET_1_KEY}
            exec.output_note::add_asset
            # => []

            # create output note 2
            push.{recipient_2}
            push.{PUBLIC_NOTE}
            push.{tag_2}
            exec.output_note::create
            # => [note_idx]

            dup
            push.{ASSET_2_VALUE}
            push.{ASSET_2_KEY}
            exec.output_note::add_asset
            # => [note_idx]

            push.{ATTACHMENT2}
            push.{attachment_scheme2}
            movup.5
            # => [note_idx, attachment_scheme, ATTACHMENT]
            exec.output_note::set_array_attachment
            # => []

            # compute the output notes commitment
            exec.tx::get_output_notes_commitment
            # => [OUTPUT_NOTES_COMMITMENT]

            # truncate the stack
            exec.sys::truncate_stack
            # => [OUTPUT_NOTES_COMMITMENT]
        end
        ",
        PUBLIC_NOTE = NoteType::Public as u8,
        recipient_1 = output_note_1.recipient().digest(),
        tag_1 = output_note_1.metadata().tag(),
        ASSET_1_KEY = asset_1.to_key_word(),
        ASSET_1_VALUE = asset_1.to_value_word(),
        recipient_2 = output_note_2.recipient().digest(),
        tag_2 = output_note_2.metadata().tag(),
        ASSET_2_KEY = asset_2.to_key_word(),
        ASSET_2_VALUE = asset_2.to_value_word(),
        ATTACHMENT2 = output_note_2.metadata().to_attachment_word(),
        attachment_scheme2 = output_note_2.metadata().attachment().attachment_scheme().as_u32(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_kernel_mem_element(NUM_OUTPUT_NOTES_PTR),
        Felt::from(2u32),
        "The test creates two notes",
    );
    assert_eq!(
        exec_output
            .get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_METADATA_HEADER_OFFSET),
        output_note_1.metadata().to_header_word(),
        "Validate the output note 1 metadata header",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ATTACHMENT_OFFSET),
        output_note_1.metadata().to_attachment_word(),
        "Validate the output note 1 attachment",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_METADATA_HEADER_OFFSET + NOTE_MEM_SIZE
        ),
        output_note_2.metadata().to_header_word(),
        "Validate the output note 2 metadata header",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ATTACHMENT_OFFSET + NOTE_MEM_SIZE
        ),
        output_note_2.metadata().to_attachment_word(),
        "Validate the output note 2 attachment",
    );

    assert_eq!(exec_output.get_stack_word(0), expected_output_notes_commitment);
    Ok(())
}

#[tokio::test]
async fn test_create_note_and_add_asset() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET)?;
    let recipient = Word::from([0, 1, 2, 3u32]);
    let tag = NoteTag::with_account_target(faucet_id);
    let asset = FungibleAsset::new(faucet_id, 10)?;

    let code = format!(
        "
        use miden::protocol::output_note

        use $kernel::prologue

        begin
            exec.prologue::prepare_transaction

            push.{recipient}
            push.{PUBLIC_NOTE}
            push.{tag}

            exec.output_note::create
            # => [note_idx]

            # assert that the index of the created note equals zero
            dup assertz.err=\"index of the created note should be zero\"
            # => [note_idx]

            push.{ASSET_VALUE}
            push.{ASSET_KEY}
            # => [ASSET_KEY, ASSET_VALUE, note_idx]

            call.output_note::add_asset
            # => []

            # truncate the stack
            dropw dropw dropw
        end
        ",
        recipient = recipient,
        PUBLIC_NOTE = NoteType::Public as u8,
        tag = tag,
        ASSET_KEY = asset.to_key_word(),
        ASSET_VALUE = asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET),
        asset.to_key_word(),
        "asset key must be stored at the correct memory location",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET + 4),
        asset.to_value_word(),
        "asset value must be stored at the correct memory location",
    );

    Ok(())
}

#[tokio::test]
async fn test_create_note_and_add_multiple_assets() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let faucet = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET)?;
    let faucet_2 = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_2)?;

    let recipient = Word::from([0, 1, 2, 3u32]);
    let tag = NoteTag::with_account_target(faucet_2);

    let asset = FungibleAsset::new(faucet, 10)?;
    let asset_2 = FungibleAsset::new(faucet_2, 20)?;
    let asset_3 = FungibleAsset::new(faucet_2, 30)?;
    let asset_2_plus_3 = FungibleAsset::new(faucet_2, 50)?;

    let non_fungible_asset = NonFungibleAsset::mock(&NON_FUNGIBLE_ASSET_DATA_2);

    let code = format!(
        "
        use miden::protocol::output_note
        use $kernel::prologue

        begin
            exec.prologue::prepare_transaction

            push.{recipient}
            push.{PUBLIC_NOTE}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            # assert that the index of the created note equals zero
            dup assertz.err=\"index of the created note should be zero\"
            # => [note_idx]

            dup
            push.{ASSET_VALUE}
            push.{ASSET_KEY}
            exec.output_note::add_asset
            # => [note_idx]

            dup
            push.{ASSET2_VALUE}
            push.{ASSET2_KEY}
            exec.output_note::add_asset
            # => [note_idx]

            dup
            push.{ASSET3_VALUE}
            push.{ASSET3_KEY}
            exec.output_note::add_asset
            # => [note_idx]

            push.{ASSET4_VALUE}
            push.{ASSET4_KEY}
            exec.output_note::add_asset
            # => []

            # truncate the stack
            repeat.7 dropw end
        end
        ",
        recipient = recipient,
        PUBLIC_NOTE = NoteType::Public as u8,
        tag = tag,
        ASSET_KEY = asset.to_key_word(),
        ASSET_VALUE = asset.to_value_word(),
        ASSET2_KEY = asset_2.to_key_word(),
        ASSET2_VALUE = asset_2.to_value_word(),
        ASSET3_KEY = asset_3.to_key_word(),
        ASSET3_VALUE = asset_3.to_value_word(),
        ASSET4_KEY = non_fungible_asset.to_key_word(),
        ASSET4_VALUE = non_fungible_asset.to_value_word(),
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output
            .get_kernel_mem_element(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_NUM_ASSETS_OFFSET)
            .as_canonical_u64(),
        3,
        "unexpected number of assets in output note",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET),
        asset.to_key_word(),
        "asset key must be stored at the correct memory location",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET + ASSET_VALUE_OFFSET
        ),
        asset.to_value_word(),
        "asset value must be stored at the correct memory location",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET + ASSET_SIZE
        ),
        asset_2_plus_3.to_key_word(),
        "asset key must be stored at the correct memory location",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET
                + OUTPUT_NOTE_ASSETS_OFFSET
                + ASSET_SIZE
                + ASSET_VALUE_OFFSET
        ),
        asset_2_plus_3.to_value_word(),
        "asset value must be stored at the correct memory location",
    );

    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_ASSETS_OFFSET + ASSET_SIZE * 2
        ),
        non_fungible_asset.to_key_word(),
        "asset key must be stored at the correct memory location",
    );
    assert_eq!(
        exec_output.get_kernel_mem_word(
            OUTPUT_NOTE_SECTION_OFFSET
                + OUTPUT_NOTE_ASSETS_OFFSET
                + ASSET_SIZE * 2
                + ASSET_VALUE_OFFSET
        ),
        non_fungible_asset.to_value_word(),
        "asset value must be stored at the correct memory location",
    );

    Ok(())
}

#[tokio::test]
async fn test_create_note_and_add_same_nft_twice() -> anyhow::Result<()> {
    let tx_context = TransactionContextBuilder::with_existing_mock_account().build()?;

    let recipient = Word::from([0, 1, 2, 3u32]);
    let tag = NoteTag::new(999 << 16 | 777);
    let non_fungible_asset = NonFungibleAsset::mock(&[1, 2, 3]);

    let code = format!(
        "
        use $kernel::prologue
        use miden::protocol::output_note

        begin
            exec.prologue::prepare_transaction
            # => []

            push.{recipient}
            push.{PUBLIC_NOTE}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            dup
            push.{ASSET_VALUE}
            push.{ASSET_KEY}
            # => [ASSET_KEY, ASSET_VALUE, note_idx, note_idx]

            exec.output_note::add_asset
            # => [note_idx]

            push.{ASSET_VALUE}
            push.{ASSET_KEY}
            exec.output_note::add_asset
            # => []
        end
        ",
        recipient = recipient,
        PUBLIC_NOTE = NoteType::Public as u8,
        tag = tag,
        ASSET_KEY = non_fungible_asset.to_key_word(),
        ASSET_VALUE = non_fungible_asset.to_value_word(),
    );

    let exec_output = tx_context.execute_code(&code).await;

    assert_execution_error!(exec_output, ERR_NON_FUNGIBLE_ASSET_ALREADY_EXISTS);
    Ok(())
}

/// Tests that creating a note with a fungible asset with amount zero works.
#[tokio::test]
async fn creating_note_with_fungible_asset_amount_zero_works() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();
    let account = builder.add_existing_mock_account(Auth::IncrNonce)?;
    let output_note = builder.add_p2id_note(
        account.id(),
        account.id(),
        &[FungibleAsset::mock(0)],
        NoteType::Private,
    )?;
    let input_note = builder.add_spawn_note([&output_note])?;
    let chain = builder.build()?;

    chain
        .build_tx_context(account, &[input_note.id()], &[])?
        .build()?
        .execute()
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_build_recipient_hash() -> anyhow::Result<()> {
    let tx_context = {
        let account =
            Account::mock(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE, Auth::IncrNonce);

        let input_note_1 = create_public_p2any_note(
            ACCOUNT_ID_SENDER.try_into().unwrap(),
            [FungibleAsset::mock(100)],
        );
        TransactionContextBuilder::new(account)
            .extend_input_notes(vec![input_note_1])
            .build()?
    };
    let input_note_1 = tx_context.tx_inputs().input_notes().get_note(0).note();

    // create output note
    let output_serial_no = Word::from([0, 1, 2, 3u32]);
    let tag = NoteTag::new(42 << 16 | 42);
    let single_input = 2;
    let storage = NoteStorage::new(vec![Felt::new(single_input)]).unwrap();
    let storage_commitment = storage.commitment();

    let recipient = NoteRecipient::new(output_serial_no, input_note_1.script().clone(), storage);
    let code = format!(
        "
        use $kernel::prologue
        use miden::protocol::output_note
        use miden::protocol::note
        use miden::core::sys

        begin
            exec.prologue::prepare_transaction

            # storage
            push.{storage_commitment}
            # SCRIPT_ROOT
            push.{script_root}
            # SERIAL_NUM
            push.{output_serial_no}
            # => [SERIAL_NUM, SCRIPT_ROOT, STORAGE_COMMITMENT]

            exec.note::build_recipient_hash
            # => [RECIPIENT, pad(12)]

            push.{PUBLIC_NOTE}
            push.{tag}
            # => [tag, note_type, RECIPIENT]

            exec.output_note::create
            # => [note_idx]

            # clean the stack
            exec.sys::truncate_stack
        end
        ",
        script_root = input_note_1.script().clone().root(),
        output_serial_no = output_serial_no,
        PUBLIC_NOTE = NoteType::Public as u8,
        tag = tag,
    );

    let exec_output = &tx_context.execute_code(&code).await?;

    assert_eq!(
        exec_output.get_kernel_mem_element(NUM_OUTPUT_NOTES_PTR),
        Felt::from(1u32),
        "number of output notes must increment by 1",
    );

    let recipient_digest = recipient.clone().digest();

    assert_eq!(
        exec_output.get_kernel_mem_word(OUTPUT_NOTE_SECTION_OFFSET + OUTPUT_NOTE_RECIPIENT_OFFSET),
        recipient_digest,
        "recipient hash not correct",
    );
    Ok(())
}

/// This test creates an output note and then adds some assets into it checking the assets info on
/// each stage.
///
/// Namely, we invoke the `miden::protocol::output_notes::get_assets_info` procedure:
/// - After adding the first `asset_0` to the note.
/// - Right after the previous check to make sure it returns the same commitment from the cached
///   data.
/// - After adding the second `asset_1` to the note.
#[tokio::test]
async fn test_get_asset_info() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();

    let fungible_asset_0 = Asset::Fungible(
        FungibleAsset::new(
            AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).expect("id should be valid"),
            5,
        )
        .expect("asset is invalid"),
    );

    // create the second asset with the different faucet ID to increase the number of assets in the
    // output note to 2.
    let fungible_asset_1 = Asset::Fungible(
        FungibleAsset::new(
            AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).expect("id should be valid"),
            5,
        )
        .expect("asset is invalid"),
    );

    let account = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        [fungible_asset_0, fungible_asset_1],
    )?;

    let mock_chain = builder.build()?;

    let output_note_0 = P2idNote::create(
        account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE.try_into()?,
        vec![fungible_asset_0],
        NoteType::Public,
        NoteAttachment::default(),
        &mut RandomCoin::new(Word::from([1, 2, 3, 4u32])),
    )?;

    let output_note_1 = P2idNote::create(
        account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE.try_into()?,
        vec![fungible_asset_0, fungible_asset_1],
        NoteType::Public,
        NoteAttachment::default(),
        &mut RandomCoin::new(Word::from([4, 3, 2, 1u32])),
    )?;

    let tx_script_src = &format!(
        r#"
        use miden::protocol::output_note
        use miden::core::sys

        begin
            # create an output note with fungible asset 0
            push.{RECIPIENT}
            push.{note_type}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            # move the asset 0 to the note
            dup
            push.{ASSET_0_VALUE}
            push.{ASSET_0_KEY}
            call.::miden::standards::wallets::basic::move_asset_to_note
            # => [note_idx]

            # get the assets hash and assets number of the note having only asset_0
            dup exec.output_note::get_assets_info
            # => [ASSETS_COMMITMENT_0, num_assets_0, note_idx]

            # assert the correctness of the assets hash
            push.{COMPUTED_ASSETS_COMMITMENT_0}
            assert_eqw.err="assets commitment of the note having only asset_0 is incorrect"
            # => [num_assets_0, note_idx]

            # assert the number of assets
            push.{assets_number_0}
            assert_eq.err="number of assets in the note having only asset_0 is incorrect"
            # => [note_idx]

            # get the assets info once more to get the cached data and assert that this data didn't
            # change
            dup exec.output_note::get_assets_info
            push.{COMPUTED_ASSETS_COMMITMENT_0}
            assert_eqw.err="assets commitment of the note having only asset_0 is incorrect"
            push.{assets_number_0}
            assert_eq.err="number of assets in the note having only asset_0 is incorrect"
            # => [note_idx]

            # add asset_1 to the note
            dup
            push.{ASSET_1_VALUE}
            push.{ASSET_1_KEY}
            call.::miden::standards::wallets::basic::move_asset_to_note
            # => [note_idx]

            # get the assets hash and assets number of the note having asset_0 and asset_1
            dup exec.output_note::get_assets_info
            # => [ASSETS_COMMITMENT_1, num_assets_1, note_idx]

            # assert the correctness of the assets hash
            push.{COMPUTED_ASSETS_COMMITMENT_1}
            assert_eqw.err="assets commitment of the note having asset_0 and asset_1 is incorrect"
            # => [num_assets_1, note_idx]

            # assert the number of assets
            push.{assets_number_1}
            assert_eq.err="number of assets in the note having asset_0 and asset_1 is incorrect"
            # => [note_idx]

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        // output note
        RECIPIENT = output_note_1.recipient().digest(),
        note_type = NoteType::Public as u8,
        tag = output_note_1.metadata().tag(),
        ASSET_0_VALUE = fungible_asset_0.to_value_word(),
        ASSET_0_KEY = fungible_asset_0.to_key_word(),
        // first data request
        COMPUTED_ASSETS_COMMITMENT_0 = output_note_0.assets().commitment(),
        assets_number_0 = output_note_0.assets().num_assets(),
        // second data request
        ASSET_1_VALUE = fungible_asset_1.to_value_word(),
        ASSET_1_KEY = fungible_asset_1.to_key_word(),
        COMPUTED_ASSETS_COMMITMENT_1 = output_note_1.assets().commitment(),
        assets_number_1 = output_note_1.assets().num_assets(),
    );

    let tx_script = CodeBuilder::default().compile_tx_script(tx_script_src)?;

    let tx_context = mock_chain
        .build_tx_context(account.id(), &[], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note_1)])
        .tx_script(tx_script)
        .build()?;

    tx_context.execute().await?;

    Ok(())
}

/// Check that recipient and metadata of a note with one asset obtained from the
/// `output_note::get_recipient` procedure is correct.
#[tokio::test]
async fn test_get_recipient_and_metadata() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();

    let account = builder.add_existing_wallet_with_assets(
        Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        [FungibleAsset::mock(2000)],
    )?;

    let mock_chain = builder.build()?;

    let output_note = P2idNote::create(
        account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE.try_into()?,
        vec![FungibleAsset::mock(5)],
        NoteType::Public,
        NoteAttachment::default(),
        &mut RandomCoin::new(Word::from([1, 2, 3, 4u32])),
    )?;

    let tx_script_src = &format!(
        r#"
        use miden::protocol::output_note
        use miden::core::sys

        begin
            # create an output note with one asset
            {output_note} drop
            # => []

            # get the recipient (the only existing note has 0'th index)
            push.0
            exec.output_note::get_recipient
            # => [RECIPIENT]

            # assert the correctness of the recipient
            push.{RECIPIENT}
            assert_eqw.err="requested note has incorrect recipient"
            # => []

            # get the metadata (the only existing note has 0'th index)
            push.0
            exec.output_note::get_metadata
            # => [NOTE_ATTACHMENT, METADATA_HEADER]

            push.{NOTE_ATTACHMENT}
            assert_eqw.err="requested note has incorrect note attachment"
            # => [METADATA_HEADER]

            push.{METADATA_HEADER}
            assert_eqw.err="requested note has incorrect metadata header"
            # => []

            # truncate the stack
            exec.sys::truncate_stack
        end
        "#,
        output_note = create_output_note(&output_note),
        RECIPIENT = output_note.recipient().digest(),
        METADATA_HEADER = output_note.metadata().to_header_word(),
        NOTE_ATTACHMENT = output_note.metadata().to_attachment_word(),
    );

    let tx_script = CodeBuilder::default().compile_tx_script(tx_script_src)?;

    let tx_context = mock_chain
        .build_tx_context(account.id(), &[], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note)])
        .tx_script(tx_script)
        .build()?;

    tx_context.execute().await?;

    Ok(())
}

/// Check that the assets number and assets data obtained from the `output_note::get_assets`
/// procedure is correct for each note with zero, one and two different assets.
#[tokio::test]
async fn test_get_assets() -> anyhow::Result<()> {
    let TestSetup {
        mock_chain,
        account,
        p2id_note_0_assets,
        p2id_note_1_asset,
        p2id_note_2_assets,
    } = setup_test()?;

    fn check_assets_code(note_index: u8, dest_ptr: u8, note: &Note) -> String {
        let mut check_assets_code = format!(
            r#"
            # push the note index and memory destination pointer
            push.{note_idx} push.{dest_ptr}
            # => [dest_ptr, note_index]

            # write the assets to memory
            exec.output_note::get_assets
            # => [num_assets, dest_ptr, note_index]

            # assert the number of note assets
            push.{assets_number}
            assert_eq.err="expected note {note_index} to have {assets_number} assets"
            # => [dest_ptr, note_index]
        "#,
            note_idx = note_index,
            dest_ptr = dest_ptr,
            assets_number = note.assets().num_assets(),
        );

        // check each asset in the note
        for (asset_index, asset) in note.assets().iter().enumerate() {
            check_assets_code.push_str(&format!(
                r#"
                    # load the asset stored in memory
                    padw dup.4 mem_loadw_le
                    # => [STORED_ASSET_KEY, dest_ptr, note_index]

                    # assert the asset key matches
                    push.{NOTE_ASSET_KEY}
                    assert_eqw.err="expected asset key at asset index {asset_index} of the note\
                    {note_index} to be {NOTE_ASSET_KEY}"
                    # => [dest_ptr, note_index]

                    # load the asset stored in memory
                    padw dup.4 add.{ASSET_VALUE_OFFSET} mem_loadw_le
                    # => [STORED_ASSET_VALUE, dest_ptr, note_index]

                    # assert the asset value matches
                    push.{NOTE_ASSET_VALUE}
                    assert_eqw.err="expected asset value at asset index {asset_index} of the note\
                    {note_index} to be {NOTE_ASSET_VALUE}"
                    # => [dest_ptr, note_index]

                    # move the pointer
                    add.{ASSET_SIZE}
                    # => [dest_ptr+ASSET_SIZE, note_index]
                "#,
                NOTE_ASSET_KEY = asset.to_key_word(),
                NOTE_ASSET_VALUE = asset.to_value_word(),
                asset_index = asset_index,
                note_index = note_index,
            ));
        }

        // drop the final `dest_ptr` and `note_index` from the stack
        check_assets_code.push_str("\ndrop drop");

        check_assets_code
    }

    let tx_script_src = &format!(
        "
        use miden::protocol::output_note
        use miden::core::sys

        begin
            {create_note_0}
            {check_note_0}

            {create_note_1}
            {check_note_1}

            {create_note_2}
            {check_note_2}

            # truncate the stack
            exec.sys::truncate_stack
        end
        ",
        create_note_0 = create_output_note(&p2id_note_0_assets),
        check_note_0 = check_assets_code(0, 0, &p2id_note_0_assets),
        create_note_1 = create_output_note(&p2id_note_1_asset),
        check_note_1 = check_assets_code(1, 8, &p2id_note_1_asset),
        create_note_2 = create_output_note(&p2id_note_2_assets),
        check_note_2 = check_assets_code(2, 16, &p2id_note_2_assets),
    );

    let tx_script = CodeBuilder::default().compile_tx_script(tx_script_src)?;

    let tx_context = mock_chain
        .build_tx_context(account.id(), &[], &[])?
        .extend_expected_output_notes(vec![
            RawOutputNote::Full(p2id_note_0_assets),
            RawOutputNote::Full(p2id_note_1_asset),
            RawOutputNote::Full(p2id_note_2_assets),
        ])
        .tx_script(tx_script)
        .build()?;

    tx_context.execute().await?;

    Ok(())
}

#[tokio::test]
async fn test_set_none_attachment() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET, Auth::IncrNonce);
    let rng = RandomCoin::new(Word::from([1, 2, 3, 4u32]));
    let attachment = NoteAttachment::default();
    let output_note =
        RawOutputNote::Full(NoteBuilder::new(account.id(), rng).attachment(attachment).build()?);

    let tx_script = format!(
        "
        use miden::protocol::output_note

        begin
            push.{RECIPIENT}
            push.{note_type}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            push.{ATTACHMENT}
            push.{attachment_kind}
            push.{attachment_scheme}
            movup.6
            # => [note_idx, attachment_scheme, attachment_kind, ATTACHMENT]
            exec.output_note::set_attachment
            # => []

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        RECIPIENT = output_note.recipient().unwrap().digest(),
        note_type = output_note.metadata().note_type() as u8,
        tag = output_note.metadata().tag().as_u32(),
        ATTACHMENT = output_note.metadata().to_attachment_word(),
        attachment_kind = output_note.metadata().attachment().content().attachment_kind().as_u8(),
        attachment_scheme = output_note.metadata().attachment().attachment_scheme().as_u32(),
    );

    let tx_script = CodeBuilder::new().compile_tx_script(tx_script)?;

    let tx = TransactionContextBuilder::new(account)
        .extend_expected_output_notes(vec![output_note.clone()])
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    let actual_note = tx.output_notes().get_note(0);
    assert_eq!(actual_note.header(), output_note.header());
    assert_eq!(actual_note.assets(), output_note.assets());

    Ok(())
}

#[tokio::test]
async fn test_set_word_attachment() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET, Auth::IncrNonce);
    let rng = RandomCoin::new(Word::from([1, 2, 3, 4u32]));
    let attachment =
        NoteAttachment::new_word(NoteAttachmentScheme::new(u32::MAX), Word::from([3, 4, 5, 6u32]));
    let output_note =
        RawOutputNote::Full(NoteBuilder::new(account.id(), rng).attachment(attachment).build()?);

    let tx_script = format!(
        "
        use miden::protocol::output_note

        begin
            push.{RECIPIENT}
            push.{note_type}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            push.{ATTACHMENT}
            push.{attachment_scheme}
            movup.5
            # => [note_idx, attachment_scheme, ATTACHMENT]
            exec.output_note::set_word_attachment
            # => []

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        RECIPIENT = output_note.recipient().unwrap().digest(),
        note_type = output_note.metadata().note_type() as u8,
        tag = output_note.metadata().tag().as_u32(),
        attachment_scheme = output_note.metadata().attachment().attachment_scheme().as_u32(),
        ATTACHMENT = output_note.metadata().to_attachment_word(),
    );

    let tx_script = CodeBuilder::new().compile_tx_script(tx_script)?;

    let tx = TransactionContextBuilder::new(account)
        .extend_expected_output_notes(vec![output_note.clone()])
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    let actual_note = tx.output_notes().get_note(0);
    assert_eq!(actual_note.header(), output_note.header());
    assert_eq!(actual_note.assets(), output_note.assets());

    Ok(())
}

#[tokio::test]
async fn test_set_array_attachment() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET, Auth::IncrNonce);
    let rng = RandomCoin::new(Word::from([1, 2, 3, 4u32]));
    let elements = [3, 4, 5, 6, 7, 8, 9u32].map(Felt::from).to_vec();
    let attachment = NoteAttachment::new_array(NoteAttachmentScheme::new(42), elements.clone())?;
    let output_note =
        RawOutputNote::Full(NoteBuilder::new(account.id(), rng).attachment(attachment).build()?);

    let tx_script = format!(
        "
        use miden::protocol::output_note

        begin
            push.{RECIPIENT}
            push.{note_type}
            push.{tag}
            exec.output_note::create
            # => [note_idx]

            push.{ATTACHMENT}
            push.{attachment_scheme}
            movup.5
            # => [note_idx, attachment_scheme, ATTACHMENT]
            exec.output_note::set_array_attachment
            # => []

            # truncate the stack
            swapdw dropw dropw
        end
        ",
        RECIPIENT = output_note.recipient().unwrap().digest(),
        note_type = output_note.metadata().note_type() as u8,
        tag = output_note.metadata().tag().as_u32(),
        attachment_scheme = output_note.metadata().attachment().attachment_scheme().as_u32(),
        ATTACHMENT = output_note.metadata().to_attachment_word(),
    );

    let tx_script = CodeBuilder::new().compile_tx_script(tx_script)?;

    let tx = TransactionContextBuilder::new(account)
        .extend_expected_output_notes(vec![output_note.clone()])
        .tx_script(tx_script)
        .extend_advice_map(vec![(output_note.metadata().to_attachment_word(), elements)])
        .build()?
        .execute()
        .await?;

    let actual_note = tx.output_notes().get_note(0);
    assert_eq!(actual_note.header(), output_note.header());
    assert_eq!(actual_note.assets(), output_note.assets());

    Ok(())
}

/// Tests creating an output note with an attachment of type NetworkAccountTarget.
#[tokio::test]
async fn test_set_network_target_account_attachment() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET, Auth::IncrNonce);
    let rng = RandomCoin::new(Word::from([1, 2, 3, 4u32]));
    let attachment = NetworkAccountTarget::new(
        ACCOUNT_ID_NETWORK_NON_FUNGIBLE_FAUCET.try_into()?,
        NoteExecutionHint::on_block_slot(5, 32, 3),
    )?;
    let output_note = NoteBuilder::new(account.id(), rng)
        .note_type(NoteType::Private)
        .attachment(attachment)
        .build()?;
    let spawn_note = create_spawn_note([&output_note])?;

    let tx = TransactionContextBuilder::new(account)
        .extend_input_notes([spawn_note].to_vec())
        .build()?
        .execute()
        .await?;

    let actual_note = tx.output_notes().get_note(0);
    assert_eq!(actual_note.header(), output_note.header());
    assert_eq!(actual_note.assets(), output_note.assets());

    // Make sure we can deserialize the attachment back into its original type.
    let actual_attachment = NetworkAccountTarget::try_from(actual_note.metadata().attachment())?;
    assert_eq!(actual_attachment, attachment);

    Ok(())
}

#[tokio::test]
async fn test_network_note() -> anyhow::Result<()> {
    let sender = Account::mock(ACCOUNT_ID_PRIVATE_FUNGIBLE_FAUCET, Auth::IncrNonce);
    let mut rng = RandomCoin::new(Word::from([9, 8, 7, 6u32]));

    // --- Valid network note ---
    let target_id = AccountId::try_from(ACCOUNT_ID_NETWORK_NON_FUNGIBLE_FAUCET)?;
    let attachment = NetworkAccountTarget::new(target_id, NoteExecutionHint::Always)?;

    let note = NoteBuilder::new(sender.id(), &mut rng)
        .note_type(NoteType::Public)
        .attachment(attachment)
        .build()?;

    // is_network_note() returns true for a note with a valid NetworkAccountTarget attachment.
    assert!(note.is_network_note());

    // into_account_target_network_note() succeeds and accessors return correct values.
    let expected_note_type = note.metadata().note_type();
    let network_note = note.into_account_target_network_note()?;
    assert_eq!(network_note.target_account_id(), target_id);
    assert_eq!(network_note.execution_hint(), NoteExecutionHint::Always);
    assert_eq!(network_note.note_type(), expected_note_type);

    // TryFrom<Note> succeeds for a valid network note.
    let valid_note = NoteBuilder::new(sender.id(), &mut rng)
        .note_type(NoteType::Public)
        .attachment(attachment)
        .build()?;
    let try_from_note = AccountTargetNetworkNote::try_from(valid_note)?;
    assert_eq!(try_from_note.target_account_id(), target_id);

    // --- Invalid: note with default (empty) attachment ---
    let non_network_note =
        NoteBuilder::new(sender.id(), &mut rng).note_type(NoteType::Public).build()?;

    // is_network_note() returns false for a note without a NetworkAccountTarget attachment.
    assert!(!non_network_note.is_network_note());

    // AccountTargetNetworkNote::new() fails for an invalid attachment.
    assert!(AccountTargetNetworkNote::new(non_network_note.clone()).is_err());

    // into_account_target_network_note() fails for a non-network note.
    assert!(non_network_note.clone().into_account_target_network_note().is_err());

    // TryFrom<Note> fails for a non-network note.
    assert!(AccountTargetNetworkNote::try_from(non_network_note).is_err());

    // --- Invalid: private note with valid NetworkAccountTarget attachment ---
    let private_network_note = NoteBuilder::new(sender.id(), &mut rng)
        .note_type(NoteType::Private)
        .attachment(attachment)
        .build()?;

    // is_network_note() returns false for a private note even with a valid attachment.
    assert!(!private_network_note.is_network_note());

    // AccountTargetNetworkNote::new() fails for a private note.
    assert!(AccountTargetNetworkNote::new(private_network_note.clone()).is_err());

    // into_account_target_network_note() fails for a private note.
    assert!(private_network_note.clone().into_account_target_network_note().is_err());

    // TryFrom<Note> fails for a private note.
    assert!(AccountTargetNetworkNote::try_from(private_network_note).is_err());

    Ok(())
}

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

/// Returns a `masm` code which creates an output note and adds some assets to it.
///
/// Data for the created output note and moved assets is obtained from the provided note.
fn create_output_note(note: &Note) -> String {
    let mut create_note_code = format!(
        "
        # create an output note
        push.{RECIPIENT}
        push.{note_type}
        push.{tag}
        exec.output_note::create
        # => [note_idx]
    ",
        RECIPIENT = note.recipient().digest(),
        note_type = note.metadata().note_type() as u8,
        tag = Felt::from(note.metadata().tag()),
    );

    for asset in note.assets().iter() {
        create_note_code.push_str(&format!(
            "
            # move the asset to the note
            dup
            push.{ASSET_VALUE}
            push.{ASSET_KEY}
            # => [ASSET_KEY, ASSET_VALUE, note_idx, note_idx]
            call.::miden::standards::wallets::basic::move_asset_to_note
            # => [note_idx]
        ",
            ASSET_KEY = asset.to_key_word(),
            ASSET_VALUE = asset.to_value_word()
        ));
    }

    create_note_code
}