miden-testing 0.15.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
use alloc::sync::Arc;
use core::slice;
use std::collections::BTreeMap;

use anyhow::Context;
use assert_matches::assert_matches;
use miden_crypto::rand::RandomCoin;
use miden_protocol::Word;
use miden_protocol::account::{Account, AccountId, AccountType};
use miden_protocol::asset::NonFungibleAsset;
use miden_protocol::batch::ProposedBatch;
use miden_protocol::block::BlockNumber;
use miden_protocol::crypto::merkle::MerkleError;
use miden_protocol::errors::{BatchAccountUpdateError, ProposedBatchError};
use miden_protocol::note::{
    Note,
    NoteAssets,
    NoteAttachments,
    NoteTag,
    NoteType,
    PartialNote,
    PartialNoteMetadata,
};
use miden_protocol::testing::account_id::AccountIdBuilder;
use miden_protocol::transaction::{
    InputNote,
    InputNoteCommitment,
    OutputNote,
    PartialBlockchain,
    ProvenTransaction,
    RawOutputNote,
};
use miden_standards::account::interface::{AccountInterface, AccountInterfaceExt};
use miden_standards::note::P2idNoteStorage;
use miden_standards::testing::account_component::MockAccountComponent;
use miden_standards::testing::note::NoteBuilder;
use miden_tx::LocalTransactionProver;
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};

use super::proven_tx_builder::MockProvenTxBuilder;
use crate::utils::create_p2any_note;
use crate::{AccountState, Auth, MockChain, MockChainBuilder};

fn mock_account_id(num: u8) -> AccountId {
    AccountIdBuilder::new().build_with_rng(&mut SmallRng::from_seed([num; 32]))
}

pub fn mock_note(num: u8) -> Note {
    let sender = mock_account_id(num);
    NoteBuilder::new(sender, SmallRng::from_seed([num; 32])).build().unwrap()
}

pub fn mock_output_note(num: u8) -> OutputNote {
    RawOutputNote::Full(mock_note(num)).into_output_note().unwrap()
}

struct TestSetup {
    chain: MockChain,
    account1: Account,
    account2: Account,
    note1: Note,
}

fn setup_chain() -> TestSetup {
    let mut builder = MockChain::builder();
    let account1 = generate_account(&mut builder);
    let account2 = generate_account(&mut builder);
    let note1 = builder
        .add_p2id_note(account1.id(), account2.id(), &[], NoteType::Public)
        .expect("adding p2id note1 should work");
    let mut chain = builder.build().expect("genesis should be valid");
    chain.prove_next_block().expect("valid setup");

    TestSetup { chain, account1, account2, note1 }
}

fn generate_account(chain: &mut MockChainBuilder) -> Account {
    let account_builder = Account::builder(rand::rng().random())
        .account_type(AccountType::Private)
        .with_component(MockAccountComponent::with_empty_slots());
    chain
        .add_account_from_builder(Auth::IncrNonce, account_builder, AccountState::Exists)
        .expect("failed to add pending account from builder")
}

/// Instantiates a chain and sets up the following transactions:
///
/// TX 1: Inputs [X] -> Outputs [Y]
/// TX 2: Inputs [Y] -> Outputs [X]
pub async fn setup_circular_note_dependency_test()
-> anyhow::Result<(MockChain, ProvenTransaction, ProvenTransaction)> {
    // Use a non-fungible asset whose faucet is different from the executing account.
    let asset = NonFungibleAsset::mock(&[42]);

    let mut builder = MockChain::builder();
    let account = builder.add_existing_wallet_with_assets(Auth::IncrNonce, [])?;
    let chain = builder.build()?;

    // Create two distinct p2any notes carrying the same arbitrary asset.
    let mut rng = RandomCoin::new(Word::from([1u32; 4]));
    let note_x = create_p2any_note(account.id(), NoteType::Public, [asset], &mut rng);
    let note_y = create_p2any_note(account.id(), NoteType::Public, [asset], &mut rng);

    // The notes share the same sender but have distinct IDs.
    assert_eq!(note_x.metadata().sender(), note_y.metadata().sender());
    assert_ne!(note_x.id(), note_y.id());

    let tx_script_y = AccountInterface::from_account(&account)
        .build_send_notes_script(&[PartialNote::from(note_y.clone())], None)?;
    // TX 1: consume note_x -> create note_y.
    // The tx script creates note_y with the asset out of thin air.
    let executed_tx1 = chain
        .build_tx_context(account.clone(), &[], slice::from_ref(&note_x))?
        .tx_script(tx_script_y)
        .extend_expected_output_notes(vec![RawOutputNote::Full(note_y.clone())])
        .build()?
        .execute()
        .await?;
    let proven_tx1 = LocalTransactionProver::default().prove_dummy(executed_tx1.clone())?;

    // Apply the account delta from TX1 to obtain the updated account state for TX2.
    let mut updated_account = account.clone();
    updated_account.apply_delta(executed_tx1.account_delta())?;

    let tx_script_x = AccountInterface::from_account(&account)
        .build_send_notes_script(&[PartialNote::from(note_x.clone())], None)?;
    // TX 2: consume note_y -> create note_x (output via tx script).
    let executed_tx2 = chain
        .build_tx_context(updated_account, &[], slice::from_ref(&note_y))?
        .tx_script(tx_script_x)
        .extend_expected_output_notes(vec![RawOutputNote::Full(note_x.clone())])
        .build()?
        .execute()
        .await?;
    let proven_tx2 = LocalTransactionProver::default().prove_dummy(executed_tx2)?;

    Ok((chain, proven_tx1, proven_tx2))
}

/// Tests that a note created and consumed in the same batch are erased from the input and
/// output note commitments.
#[test]
fn empty_transaction_batch() -> anyhow::Result<()> {
    let TestSetup { chain, .. } = setup_chain();
    let block1 = chain.block_header(1);

    let error =
        ProposedBatch::new(vec![], block1, chain.latest_partial_blockchain(), BTreeMap::default())
            .unwrap_err();

    assert_matches!(error, ProposedBatchError::EmptyTransactionBatch);

    Ok(())
}

/// Tests that unauthenticated notes created and consumed in transactions in a batch are rejected
/// when provided in an incorrect order.
#[test]
fn incorrectly_ordered_txs_rejected() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let note = mock_note(40);
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![RawOutputNote::Full(note.clone()).into_output_note().unwrap()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note.clone()])
            .build()?;

    // Provide the transactions in the wrong order, should be tx1, tx2.
    let error = ProposedBatch::new(
        [tx2.clone(), tx1.clone()].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::NoteConsumedBeforeCreated { note_id, consumed_by, created_by } => {
        assert_eq!(note_id, note.id());
        assert_eq!(consumed_by, tx2.id());
        assert_eq!(created_by, tx1.id());
    });

    Ok(())
}

/// Tests that a note created and consumed in the same batch are erased from the input and
/// output note commitments.
#[test]
fn note_created_and_consumed_in_same_batch() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let note = mock_note(40);
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![RawOutputNote::Full(note.clone()).into_output_note().unwrap()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note.clone()])
            .build()?;

    let batch = ProposedBatch::new(
        [tx1, tx2].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(batch.input_notes().num_notes(), 0);
    assert_eq!(batch.output_notes().len(), 0);

    Ok(())
}

/// Notes with the same details but different metadata are not considered the same for batch
/// erasure.
#[test]
fn same_details_different_metadata_not_erased_from_batch() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    // create two notes with identical details (recipient, assets, attachments) but different
    // metadata, so they have distinct note IDs

    let output_note = NoteBuilder::new(mock_account_id(7), SmallRng::from_seed([7; 32]))
        .serial_number([1, 2, 3, 4u32].into())
        .tag(100)
        .note_type(NoteType::Public)
        .build()?;

    let input_note = Note::with_attachments(
        output_note.assets().clone(),
        output_note.metadata().partial_metadata().with_tag(NoteTag::from(200)),
        output_note.recipient().clone(),
        output_note.attachments().clone(),
    );

    let output_note_proven = RawOutputNote::Full(output_note.clone()).into_output_note().unwrap();

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![output_note_proven.clone()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![input_note.clone()])
            .build()?;

    let batch = ProposedBatch::new(
        [tx1, tx2].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(
        batch.input_notes().clone().into_vec(),
        vec![InputNoteCommitment::from(&InputNote::unauthenticated(input_note))],
    );
    assert_eq!(batch.output_notes()[0], output_note_proven);

    Ok(())
}

/// Two standards P2ID output notes with identical details but different metadata should both appear
/// in the batch.
#[test]
fn two_p2id_inputs_same_details_different_metadata_in_same_batch() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let serial_num = Word::from([11, 22, 33, 44u32]);
    let recipient = P2idNoteStorage::new(account2.id()).into_recipient(serial_num);

    let note_300 = Note::with_attachments(
        NoteAssets::default(),
        PartialNoteMetadata::new(account1.id(), NoteType::Public).with_tag(NoteTag::from(300)),
        recipient.clone(),
        NoteAttachments::default(),
    );
    let note_301 = Note::with_attachments(
        NoteAssets::default(),
        PartialNoteMetadata::new(account1.id(), NoteType::Public).with_tag(NoteTag::from(301)),
        recipient,
        NoteAttachments::default(),
    );

    // Only metadata should be different.
    assert_eq!(note_300.assets(), note_301.assets());
    assert_ne!(note_300.metadata(), note_301.metadata());
    assert_eq!(note_300.recipient(), note_301.recipient());
    assert_eq!(note_300.attachments(), note_301.attachments());

    let tx =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .authenticated_notes(vec![note_300.clone(), note_301.clone()])
            .build()?;

    let batch = ProposedBatch::new(
        vec![Arc::new(tx)],
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(batch.input_notes().num_notes(), 2);

    Ok(())
}

/// Tests that an error is returned if the same unauthenticated input note appears multiple
/// times in different transactions.
#[test]
fn duplicate_unauthenticated_input_notes() -> anyhow::Result<()> {
    let TestSetup { chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);

    let note = mock_note(50);
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note.clone()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note.clone()])
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block1,
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::DuplicateInputNote {
        note_nullifier,
        first_transaction_id,
        second_transaction_id
      } if note_nullifier == note.nullifier() &&
        first_transaction_id == tx1.id() &&
        second_transaction_id == tx2.id()
    );

    Ok(())
}

/// Tests that an error is returned if the same authenticated input note appears multiple
/// times in different transactions.
#[test]
fn duplicate_authenticated_input_notes() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, note1 } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .authenticated_notes(vec![note1.clone()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .authenticated_notes(vec![note1.clone()])
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::DuplicateInputNote {
        note_nullifier,
        first_transaction_id,
        second_transaction_id
      } if note_nullifier == note1.nullifier() &&
        first_transaction_id == tx1.id() &&
        second_transaction_id == tx2.id()
    );

    Ok(())
}

/// Tests that an error is returned if the same input note appears multiple times in different
/// transactions as an unauthenticated or authenticated note.
#[test]
fn duplicate_mixed_input_notes() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, note1 } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note1.clone()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .authenticated_notes(vec![note1.clone()])
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::DuplicateInputNote {
        note_nullifier,
        first_transaction_id,
        second_transaction_id
      } if note_nullifier == note1.nullifier() &&
        first_transaction_id == tx1.id() &&
        second_transaction_id == tx2.id()
    );

    Ok(())
}

/// Tests that an error is returned if the same output note appears multiple times in different
/// transactions.
#[test]
fn duplicate_output_notes() -> anyhow::Result<()> {
    let TestSetup { chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);

    let note0 = mock_output_note(50);
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![note0.clone()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![note0.clone()])
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block1,
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::DuplicateOutputNote {
             note_id,
             first_transaction_id,
             second_transaction_id
           } if note_id == note0.id() &&
             first_transaction_id == tx1.id() &&
             second_transaction_id == tx2.id());

    Ok(())
}

/// Test that an unauthenticated input note for which a proof exists is converted into an
/// authenticated one and becomes part of the batch's input note commitment.
#[tokio::test]
async fn unauthenticated_note_converted_to_authenticated() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();
    let account1 = generate_account(&mut builder);
    let note1 = create_p2any_note(account1.id(), NoteType::Public, [], builder.rng_mut());
    let note2 = create_p2any_note(account1.id(), NoteType::Public, [], builder.rng_mut());
    let spawn_note = builder.add_spawn_note([&note1, &note2])?;
    let mut chain = builder.build()?;

    let tx = chain
        .build_tx_context(account1.clone(), &[spawn_note.id()], &[])?
        .extend_expected_output_notes(vec![
            RawOutputNote::Full(note1.clone()),
            RawOutputNote::Full(note2.clone()),
        ])
        .build()?
        .execute()
        .await?;
    chain.add_pending_executed_transaction(&tx)?;

    // Note1 and note2 are included and therefore provable against block1.
    let block1 = chain.prove_next_block()?;
    let block2 = chain.prove_next_block()?;
    let block3 = chain.prove_next_block()?;

    assert_eq!(
        block1.body().output_notes().count(),
        2,
        "block 1 should contain note1 and note2"
    );
    assert!(
        block1.body().output_notes().any(|(_, note)| note.id() == note1.id()),
        "block 1 should contain note1"
    );
    assert!(
        block1.body().output_notes().any(|(_, note)| note.id() == note2.id()),
        "block 1 should contain note2"
    );

    // Consume the authenticated note as an unauthenticated one in the transaction.
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(block2.header())
            .unauthenticated_notes(vec![note2.clone()])
            .build()?;

    let input_note1 = chain.get_public_note(&note1.id()).expect("note not found");
    let note_inclusion_proof1 = input_note1.proof().expect("note should be of type authenticated");

    let input_note2 = chain.get_public_note(&note2.id()).expect("note not found");
    let note_inclusion_proof2 = input_note2.proof().expect("note should be of type authenticated");

    // The partial blockchain will contain all blocks in the mock chain, in particular block2 which
    // both note inclusion proofs need for verification.
    let partial_blockchain = chain.latest_partial_blockchain();

    // Case 1: Error: A wrong proof is passed.
    // --------------------------------------------------------------------------------------------

    let error = ProposedBatch::new(
        [tx1.clone()].into_iter().map(Arc::new).collect(),
        block3.header().clone(),
        partial_blockchain.clone(),
        BTreeMap::from_iter([(input_note2.id(), note_inclusion_proof1.clone())]),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::UnauthenticatedNoteAuthenticationFailed {
        note_id,
        block_num,
        source: MerkleError::ConflictingRoots { .. },
      } => {
          assert_eq!(note_id, note2.id());
          assert_eq!(block_num, block1.header().block_num());
      }
    );

    // Case 2: Error: The block referenced by the (valid) note inclusion proof is missing.
    // --------------------------------------------------------------------------------------------

    // Make a clone of the partial blockchain where block1 is missing.
    let mut mmr = partial_blockchain.mmr().clone();
    mmr.untrack(block1.header().block_num().as_usize());
    let blocks = partial_blockchain
        .block_headers()
        .filter(|header| header.block_num() != block1.header().block_num())
        .cloned();

    let error = ProposedBatch::new(
        [tx1.clone()].into_iter().map(Arc::new).collect(),
        block3.header().clone(),
        PartialBlockchain::new(mmr, blocks)
            .context("failed to build partial blockchain with missing block")?,
        BTreeMap::from_iter([(input_note2.id(), note_inclusion_proof2.clone())]),
    )
    .unwrap_err();

    assert_matches!(
        error,
        ProposedBatchError::UnauthenticatedInputNoteBlockNotInPartialBlockchain {
          block_number,
          note_id
        } => {
            assert_eq!(block_number, note_inclusion_proof2.location().block_num());
            assert_eq!(note_id, input_note2.id());
        }
    );

    // Case 3: Success: The correct proof is passed.
    // --------------------------------------------------------------------------------------------

    let batch = ProposedBatch::new(
        [tx1].into_iter().map(Arc::new).collect(),
        block3.header().clone(),
        partial_blockchain,
        BTreeMap::from_iter([(input_note2.id(), note_inclusion_proof2.clone())]),
    )?;

    // We expect the unauthenticated input note to have become an authenticated one,
    // meaning it is part of the input note commitment.
    assert_eq!(batch.input_notes().num_notes(), 1);
    assert!(
        batch
            .input_notes()
            .iter()
            .any(|commitment| commitment == &InputNoteCommitment::from(&input_note2))
    );
    assert_eq!(batch.output_notes().len(), 0);

    Ok(())
}

/// Test that an authenticated input note that is also created in the same batch does not error
/// and instead is marked as consumed.
/// - This requires a nullifier collision on the input and output note which is very unlikely in
///   practice.
/// - This makes the created note unspendable as its nullifier is added to the nullifier tree.
/// - The batch kernel cannot return an error in this case as it can't detect this condition due to
///   only having the nullifier for authenticated input notes _but_ not having the nullifier for
///   private output notes.
/// - We test this to ensure the kernel does something reasonable in this case and it is not an
///   attack vector.
#[test]
fn authenticated_note_created_in_same_batch() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, account2, note1 } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let note0 = mock_note(50);
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .output_notes(vec![RawOutputNote::Full(note0.clone()).into_output_note().unwrap()])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .authenticated_notes(vec![note1.clone()])
            .build()?;

    let batch = ProposedBatch::new(
        [tx1, tx2].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(batch.input_notes().num_notes(), 1);
    assert_eq!(batch.output_notes().len(), 1);

    Ok(())
}

/// Test that multiple transactions against the same account
/// 1) can be correctly executed when in the right order,
/// 2) and that an error is returned if they are incorrectly ordered.
#[test]
fn multiple_transactions_against_same_account() -> anyhow::Result<()> {
    let TestSetup { chain, account1, .. } = setup_chain();
    let block1 = chain.block_header(1);

    // Use some random hash as the initial state commitment of tx1.
    let initial_state_commitment = Word::empty();
    let tx1 = MockProvenTxBuilder::with_account(
        account1.id(),
        initial_state_commitment,
        account1.to_commitment(),
    )
    .reference_block(&block1)
    .output_notes(vec![mock_output_note(0)])
    .build()?;

    // Use some random hash as the final state commitment of tx2.
    let final_state_commitment = mock_note(10).id().as_word();
    let tx2 = MockProvenTxBuilder::with_account(
        account1.id(),
        account1.to_commitment(),
        final_state_commitment,
    )
    .reference_block(&block1)
    .build()?;

    // Success: Transactions are correctly ordered.
    let batch = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block1.clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(batch.account_updates().len(), 1);
    // Assert that the initial state commitment from tx1 is used and the final state commitment
    // from tx2.
    assert_eq!(
        batch.account_updates().get(&account1.id()).unwrap().initial_state_commitment(),
        initial_state_commitment
    );
    assert_eq!(
        batch.account_updates().get(&account1.id()).unwrap().final_state_commitment(),
        final_state_commitment
    );

    // Error: Transactions are incorrectly ordered.
    let error = ProposedBatch::new(
        [tx2.clone(), tx1.clone()].into_iter().map(Arc::new).collect(),
        block1,
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(
        error,
        ProposedBatchError::AccountUpdateError {
            source: BatchAccountUpdateError::AccountUpdateInitialStateMismatch(tx_id),
            ..
        } if tx_id == tx1.id()
    );

    Ok(())
}

/// Tests that the input and outputs notes commitment is correctly computed.
/// - Notes created and consumed in the same batch are erased from these commitments.
/// - The input note commitment is sorted by [`Nullifier`].
/// - The output note commitment is sorted by [`NoteId`].
#[test]
fn input_and_output_notes_commitment() -> anyhow::Result<()> {
    let TestSetup { chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);

    // Randomize the note IDs and nullifiers on each test run to make sure the sorting property
    // is tested with various inputs.
    let mut rng = rand::rng();
    // Generate a single random number and derive other unique numbers from it to avoid collisions.
    let note_num = rng.random();

    let note0 = mock_output_note(note_num);
    let note1 = mock_note(note_num.wrapping_add(1));
    let note2 = mock_output_note(note_num.wrapping_add(2));
    let note3 = mock_output_note(note_num.wrapping_add(3));
    let note4 = mock_note(note_num.wrapping_add(4));
    let note5 = mock_note(note_num.wrapping_add(5));
    let note6 = mock_note(note_num.wrapping_add(6));

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note5.clone()])
            .output_notes(vec![
                RawOutputNote::Full(note1.clone()).into_output_note().unwrap(),
                note0.clone(),
            ])
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .unauthenticated_notes(vec![note1, note4.clone(), note6.clone()])
            .output_notes(vec![note2.clone(), note3.clone()])
            .build()?;

    let batch = ProposedBatch::new(
        [tx1.clone(), tx2.clone()].into_iter().map(Arc::new).collect(),
        block1,
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    // We expect note1 to be erased from the input/output notes as it is created and consumed
    // in the batch.
    let mut expected_output_notes = [note0, note2, note3];
    // We expect a vector sorted by NoteId.
    expected_output_notes.sort_unstable_by_key(OutputNote::id);

    assert_eq!(batch.output_notes().len(), 3);
    assert_eq!(batch.output_notes(), expected_output_notes);

    let mut expected_input_notes = [
        InputNoteCommitment::from(&InputNote::unauthenticated(note4)),
        InputNoteCommitment::from(&InputNote::unauthenticated(note5)),
        InputNoteCommitment::from(&InputNote::unauthenticated(note6)),
    ];
    // We expect a vector sorted by Nullifier (since input_output_note_tracker is set up that way).
    expected_input_notes.sort_unstable_by_key(InputNoteCommitment::nullifier);

    assert_eq!(batch.input_notes().num_notes(), 3);
    assert_eq!(batch.input_notes().clone().into_vec(), &expected_input_notes);

    Ok(())
}

/// Tests that the expiration block number of a batch is the minimum of all contained transactions.
#[test]
fn batch_expiration() -> anyhow::Result<()> {
    let TestSetup { chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .expiration_block_num(BlockNumber::from(35))
            .build()?;
    // This transaction has the smallest valid expiration block num that allows it to still be
    // included in the batch.
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .expiration_block_num(block1.block_num() + 1)
            .build()?;

    let batch = ProposedBatch::new(
        [tx1, tx2].into_iter().map(Arc::new).collect(),
        block1.clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    assert_eq!(batch.batch_expiration_block_num(), block1.block_num() + 1);

    Ok(())
}

/// Tests that passing duplicate transactions in a batch returns an error.
#[test]
fn duplicate_transaction() -> anyhow::Result<()> {
    let TestSetup { chain, account1, .. } = setup_chain();
    let block1 = chain.block_header(1);

    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .expiration_block_num(BlockNumber::from(35))
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx1.clone()].into_iter().map(Arc::new).collect(),
        block1,
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(error, ProposedBatchError::DuplicateTransaction { transaction_id } if transaction_id == tx1.id());

    Ok(())
}

/// Tests that transactions with a circular dependency between notes are rejected.
///
/// Both transactions execute against the same account. The two p2any notes share the same
/// sender (the executing account) and carry the same asset, but have different serial numbers
/// so that they are distinct notes with different IDs.
///
/// TX 1: Inputs [X] -> Outputs [Y]
/// TX 2: Inputs [Y] -> Outputs [X]
#[tokio::test]
async fn cross_tx_circular_note_dependency_is_rejected() -> anyhow::Result<()> {
    let (chain, proven_tx1, proven_tx2) = setup_circular_note_dependency_test().await?;

    let error = ProposedBatch::new(
        [proven_tx1, proven_tx2].into_iter().map(Arc::new).collect(),
        chain.latest_block_header(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    // A circular dependency is detected as consumption-before-creation.
    assert_matches!(error, ProposedBatchError::NoteConsumedBeforeCreated { .. });

    Ok(())
}

/// Tests that a non-fungible asset minted out of thin air cannot be used by an account in valid
/// ways.
///
/// TX 1: Inputs [X] -> Outputs [ ]
/// TX 2: Inputs [ ] -> Outputs [X]
#[tokio::test]
async fn cross_tx_circular_note_dependency_is_rejected_2() -> anyhow::Result<()> {
    // Use a non-fungible asset whose faucet is different from the executing account.
    let asset = NonFungibleAsset::mock(&[42]);

    let mut builder = MockChain::builder();
    let account = builder.add_existing_wallet_with_assets(Auth::IncrNonce, [])?;
    let chain = builder.build()?;

    // Create two distinct p2any notes carrying the same arbitrary asset.
    let mut rng = RandomCoin::new(Word::from([1u32; 4]));
    let note_x = create_p2any_note(account.id(), NoteType::Public, [asset], &mut rng);

    // TX 1: consume note_x to move the asset to the vault.
    let executed_tx1 = chain
        .build_tx_context(account.clone(), &[], slice::from_ref(&note_x))?
        .build()?
        .execute()
        .await?;
    let proven_tx1 = LocalTransactionProver::default().prove_dummy(executed_tx1.clone())?;

    // Apply the account delta from TX1 to obtain the updated account state for TX2.
    let mut updated_account = account.clone();
    updated_account.apply_delta(executed_tx1.account_delta())?;

    assert_eq!(updated_account.vault().get(asset.vault_key()).unwrap(), asset);

    let tx_script_x = AccountInterface::from_account(&account)
        .build_send_notes_script(&[PartialNote::from(note_x.clone())], None)?;
    // TX 2: create note_x with the asset from the account vault.
    let executed_tx2 = chain
        .build_tx_context(updated_account, &[], &[])?
        .tx_script(tx_script_x)
        .extend_expected_output_notes(vec![RawOutputNote::Full(note_x.clone())])
        .build()?
        .execute()
        .await?;
    assert_eq!(
        executed_tx2.output_notes().get_note(0).assets().iter().next().unwrap(),
        &asset,
        "asset should have been moved to the note"
    );
    let proven_tx2 = LocalTransactionProver::default().prove_dummy(executed_tx2)?;

    let error = ProposedBatch::new(
        [proven_tx1, proven_tx2].into_iter().map(Arc::new).collect(),
        chain.latest_block_header(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    // Tx1 cannot depend on an input note that is created by transaction 2. This circular dependency
    // is detected as consumption-before-creation.
    assert_matches!(error, ProposedBatchError::NoteConsumedBeforeCreated { .. });

    Ok(())
}

/// Tests that expired transactions cannot be included in a batch.
#[test]
fn expired_transaction() -> anyhow::Result<()> {
    let TestSetup { chain, account1, account2, .. } = setup_chain();
    let block1 = chain.block_header(1);

    // This transaction expired at the batch's reference block.
    let tx1 =
        MockProvenTxBuilder::with_account(account1.id(), Word::empty(), account1.to_commitment())
            .reference_block(&block1)
            .expiration_block_num(block1.block_num())
            .build()?;
    let tx2 =
        MockProvenTxBuilder::with_account(account2.id(), Word::empty(), account2.to_commitment())
            .reference_block(&block1)
            .expiration_block_num(block1.block_num() + 3)
            .build()?;

    let error = ProposedBatch::new(
        [tx1.clone(), tx2].into_iter().map(Arc::new).collect(),
        block1.clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(
        error,
        ProposedBatchError::ExpiredTransaction {
            transaction_id,
            transaction_expiration_num,
            reference_block_num
        }  if transaction_id == tx1.id() &&
            transaction_expiration_num == block1.block_num() &&
            reference_block_num == block1.block_num()
    );

    Ok(())
}

/// Tests that a NOOP transaction with state commitments X -> X against account A can appear
/// _before_ a state-updating transaction with state commitments X -> Y against account A.
#[test]
fn noop_tx_before_state_updating_tx_against_same_account() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, note1, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let random_final_state_commitment = Word::from([1, 2, 3, 4u32]);

    let note = mock_note(40);
    // consume a random note to make the transaction non-empty
    let noop_tx1 = MockProvenTxBuilder::with_account(
        account1.id(),
        account1.to_commitment(),
        account1.to_commitment(),
    )
    .reference_block(&block1)
    .authenticated_notes(vec![note1])
    .output_notes(vec![RawOutputNote::Full(note.clone()).into_output_note().unwrap()])
    .build()?;

    // sanity check
    assert_eq!(
        noop_tx1.account_update().initial_state_commitment(),
        noop_tx1.account_update().final_state_commitment()
    );

    let tx2 = MockProvenTxBuilder::with_account(
        account1.id(),
        account1.to_commitment(),
        random_final_state_commitment,
    )
    .reference_block(&block1)
    .unauthenticated_notes(vec![note.clone()])
    .build()?;

    let batch = ProposedBatch::new(
        [noop_tx1, tx2].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    let update = batch.account_updates().get(&account1.id()).unwrap();
    assert_eq!(update.initial_state_commitment(), account1.to_commitment());
    assert_eq!(update.final_state_commitment(), random_final_state_commitment);

    Ok(())
}

/// Tests that a transaction with a ref_block_commitment that does not match the commitment of the
/// block at the declared ref_block_num in the partial blockchain is rejected.
///
/// The test uses two independent MockChain instances so that the same block 1 has different block
/// commitments on each chain. A transaction built against chain_a's block 1 is then included in a
/// batch whose partial blockchain comes from chain_b, which has a different commitment for block 1.
#[test]
fn mismatched_ref_block_commitment_rejected() -> anyhow::Result<()> {
    let account_builder = Account::builder([42; 32])
        .account_type(AccountType::Private)
        .with_component(MockAccountComponent::with_empty_slots());

    // Build chain_a with the account.
    let mut builder1 = MockChain::builder();
    let account_a = builder1.add_account_from_builder(
        Auth::IncrNonce,
        account_builder.clone(),
        AccountState::Exists,
    )?;
    let mut chain_a = builder1.build()?;
    let chain_a_block1 = chain_a.prove_next_block()?;

    // Build chain_b with the exact same account.
    let mut builder2 = MockChain::builder();
    let account_b = builder2.add_account_from_builder(
        Auth::IncrNonce,
        account_builder,
        AccountState::Exists,
    )?;
    let mut chain_b = builder2.build()?;
    let chain_b_block1 = chain_b.prove_next_block()?;
    let chain_b_block2 = chain_b.prove_next_block()?;

    // Sanity checks: same account, different block commitments at block 1.
    assert_eq!(
        account_a.to_commitment(),
        account_b.to_commitment(),
        "accounts should have the same commitment"
    );
    assert_ne!(
        chain_a_block1.header().commitment(),
        chain_b_block1.header().commitment(),
        "block 1 should have different commitments on the two chains"
    );

    // Build a transaction that references chain_a's block 1. This means the transaction was
    // executed against a chain state that is incompatible with chain_b.
    let tx =
        MockProvenTxBuilder::with_account(account_a.id(), Word::empty(), account_a.to_commitment())
            .reference_block(chain_a_block1.header())
            .build()?;

    // chain_b's partial blockchain contains block 1, but with chain_b's commitment - not chain_a's.
    // ProposedBatch::new should reject this transaction because its ref_block_commitment doesn't
    // match the commitment of block 1 in the partial blockchain.
    let result = ProposedBatch::new(
        vec![Arc::new(tx.clone())],
        chain_b_block2.header().clone(),
        chain_b.latest_partial_blockchain(),
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(
        result,
        ProposedBatchError::TransactionReferenceBlockCommitmentMismatch {
              transaction_id, block_num, expected_block_commitment, actual_block_commitment
          } => {
            assert_eq!(transaction_id, tx.id());
            assert_eq!(block_num, tx.ref_block_num());
            assert_eq!(actual_block_commitment, tx.ref_block_commitment());
            assert_eq!(expected_block_commitment, chain_b_block1.header().commitment());
        }
    );

    // Make sure the same error occurs when the block referenced by the transaction is the same as
    // the batch reference block.
    let (ref_block, partial_blockchain) = chain_b.selective_partial_blockchain(
        chain_b_block1.header().block_num(),
        [BlockNumber::GENESIS],
    )?;
    assert_eq!(
        ref_block.block_num(),
        tx.ref_block_num(),
        "tx and batch ref block num should match"
    );

    let result = ProposedBatch::new(
        vec![Arc::new(tx.clone())],
        ref_block.clone(),
        partial_blockchain,
        BTreeMap::default(),
    )
    .unwrap_err();

    assert_matches!(
        result,
        ProposedBatchError::TransactionReferenceBlockCommitmentMismatch {
            transaction_id, block_num, expected_block_commitment, actual_block_commitment
          } => {
            assert_eq!(transaction_id, tx.id());
            assert_eq!(block_num, tx.ref_block_num());
            assert_eq!(actual_block_commitment, tx.ref_block_commitment());
            assert_eq!(expected_block_commitment, ref_block.commitment());
        }
    );

    Ok(())
}

/// Tests that a NOOP transaction with state commitments X -> X against account A can appear
/// _after_ a state-updating transaction with state commitments X -> Y against account A.
#[test]
fn noop_tx_after_state_updating_tx_against_same_account() -> anyhow::Result<()> {
    let TestSetup { mut chain, account1, note1, .. } = setup_chain();
    let block1 = chain.block_header(1);
    let block2 = chain.prove_next_block()?;

    let random_final_state_commitment = Word::from([1, 2, 3, 4u32]);

    let note = mock_note(40);

    let tx1 = MockProvenTxBuilder::with_account(
        account1.id(),
        account1.to_commitment(),
        random_final_state_commitment,
    )
    .reference_block(&block1)
    .output_notes(vec![RawOutputNote::Full(note.clone()).into_output_note().unwrap()])
    .build()?;

    // consume random notes to make the transaction non-empty
    let noop_tx2 = MockProvenTxBuilder::with_account(
        account1.id(),
        random_final_state_commitment,
        random_final_state_commitment,
    )
    .reference_block(&block1)
    .authenticated_notes(vec![note1])
    .unauthenticated_notes(vec![note.clone()])
    .build()?;

    // sanity check
    assert_eq!(
        noop_tx2.account_update().initial_state_commitment(),
        noop_tx2.account_update().final_state_commitment()
    );

    let batch = ProposedBatch::new(
        [tx1, noop_tx2].into_iter().map(Arc::new).collect(),
        block2.header().clone(),
        chain.latest_partial_blockchain(),
        BTreeMap::default(),
    )?;

    let update = batch.account_updates().get(&account1.id()).unwrap();
    assert_eq!(update.initial_state_commitment(), account1.to_commitment());
    assert_eq!(update.final_state_commitment(), random_final_state_commitment);

    Ok(())
}