miden-client-integration-tests 0.14.5

Integration Tests for the miden client library
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use assert_matches::assert_matches;
use miden_client::account::component::{AccountComponent, AccountComponentMetadata};
use miden_client::account::{
    Account,
    AccountBuilder,
    AccountId,
    AccountStorageMode,
    AccountType,
    StorageMap,
    StorageMapKey,
    StorageSlot,
    StorageSlotName,
};
use miden_client::assembly::CodeBuilder;
use miden_client::asset::{Asset, FungibleAsset};
use miden_client::auth::{AuthSchemeId, AuthSecretKey, AuthSingleSig, RPO_FALCON_SCHEME_ID};
use miden_client::builder::ClientBuilder;
use miden_client::keystore::FilesystemKeyStore;
use miden_client::note::{NoteFile, NoteType};
use miden_client::rpc::AccountStateAt;
use miden_client::rpc::domain::account::{
    AccountStorageRequirements,
    FetchedAccount,
    StorageMapEntries,
};
use miden_client::store::{
    InputNoteRecord,
    InputNoteState,
    NoteFilter,
    OutputNoteState,
    TransactionFilter,
};
use miden_client::testing::common::*;
use miden_client::transaction::{
    DiscardCause,
    PaymentNoteDescription,
    ProvenTransaction,
    TransactionInputs,
    TransactionProver,
    TransactionProverError,
    TransactionRequestBuilder,
    TransactionStatus,
};
use miden_client::{ClientError, EMPTY_WORD, Felt, Word};
use miden_client_sqlite_store::ClientBuilderSqliteExt;
use tracing::info;

use crate::tests::config::ClientConfig;

pub async fn test_client_builder_initializes_client_with_endpoint(
    client_config: ClientConfig,
) -> Result<()> {
    let (endpoint, _, store_config, auth_path) = client_config.as_parts();

    let mut client = ClientBuilder::<FilesystemKeyStore>::new()
        .grpc_client(&endpoint, Some(10_000))
        .filesystem_keystore(auth_path)?
        .sqlite_store(store_config)
        .in_debug_mode(miden_client::DebugMode::Enabled)
        .build()
        .await?;

    assert!(client.in_debug_mode());

    let sync_summary = client.sync_state().await?;

    assert!(sync_summary.block_num.as_u32() > 0);
    Ok(())
}

pub async fn test_multiple_tx_on_same_block(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;
    wait_for_node(&mut client).await;

    let (first_regular_account, second_regular_account, faucet_account_header) =
        setup_two_wallets_and_faucet(
            &mut client,
            AccountStorageMode::Private,
            &authenticator,
            RPO_FALCON_SCHEME_ID,
        )
        .await?;
    let from_account_id = first_regular_account.id();
    let to_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    // First Mint necessary token
    let tx_id =
        mint_and_consume(&mut client, from_account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client, tx_id).await?;

    // Do a transfer from first account to second account
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();
    let tx_request_1 = TransactionRequestBuilder::new()
        .build_pay_to_id(
            PaymentNoteDescription::new(
                vec![Asset::Fungible(asset)],
                from_account_id,
                to_account_id,
            ),
            NoteType::Private,
            client.rng(),
        )
        .unwrap();
    let tx_request_2 = TransactionRequestBuilder::new()
        .build_pay_to_id(
            PaymentNoteDescription::new(
                vec![Asset::Fungible(asset)],
                from_account_id,
                to_account_id,
            ),
            NoteType::Private,
            client.rng(),
        )
        .unwrap();

    info!(from = %from_account_id, to = %to_account_id, "Running P2ID transaction");

    // Create transactions
    let transaction_result_1 =
        client.execute_transaction(from_account_id, tx_request_1).await.unwrap();
    let transaction_id_1 = transaction_result_1.id();
    let proven_transaction_1 = client.prove_transaction(&transaction_result_1).await.unwrap();

    // NOTE: we manually construct a [`TransactionStoreUpdate`] because we want to submit both
    // proofs at the same time, but we can't apply the transaction to the store before submitting
    // it to the node (since we need the submission height).
    let current_height = client.get_sync_height().await?;
    client.apply_transaction(&transaction_result_1, current_height).await?;

    let transaction_result_2 =
        client.execute_transaction(from_account_id, tx_request_2).await.unwrap();
    let transaction_id_2 = transaction_result_2.id();
    let proven_transaction_2 = client.prove_transaction(&transaction_result_2).await.unwrap();

    client
        .submit_proven_transaction(proven_transaction_1, &transaction_result_1)
        .await?;
    let submission_height_2 = client
        .submit_proven_transaction(proven_transaction_2, &transaction_result_2)
        .await
        .unwrap();

    client
        .apply_transaction(&transaction_result_2, submission_height_2)
        .await
        .unwrap();

    client.sync_state().await.unwrap();

    // wait for 1 block
    wait_for_blocks(&mut client, 1).await;

    // wait for both transactions to be committed
    wait_for_tx(&mut client, transaction_id_1).await?;
    wait_for_tx(&mut client, transaction_id_2).await?;

    let transactions = client
        .get_transactions(TransactionFilter::All)
        .await
        .unwrap()
        .into_iter()
        .filter(|tx| tx.id == transaction_id_1 || tx.id == transaction_id_2)
        .collect::<Vec<_>>();

    assert_eq!(transactions.len(), 2);
    assert!(matches!(transactions[0].status, TransactionStatus::Committed { .. }));
    assert_eq!(transactions[0].status, transactions[1].status);

    let note_id = transactions[0].details.output_notes.iter().next().unwrap().id();
    let note = client.get_output_note(note_id).await.unwrap().unwrap();
    assert!(matches!(note.state(), OutputNoteState::CommittedFull { .. }));

    let sender_balance = client
        .account_reader(from_account_id)
        .get_balance(faucet_account_id)
        .await
        .context("failed to find sender account after transactions")?;
    assert_eq!(sender_balance, MINT_AMOUNT - (TRANSFER_AMOUNT * 2));
    Ok(())
}

pub async fn test_import_expected_notes(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator_1) = client_config.clone().into_client().await?;
    let (first_basic_account, faucet_account) = setup_wallet_and_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (mut client_2, authenticator_2) = client_config.into_client().await?;
    let (client_2_account, _) = insert_new_wallet(
        &mut client_2,
        AccountStorageMode::Private,
        &authenticator_2,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    wait_for_node(&mut client_2).await;

    let tx_request = TransactionRequestBuilder::new()
        .build_mint_fungible_asset(
            FungibleAsset::new(faucet_account.id(), MINT_AMOUNT).unwrap(),
            client_2_account.id(),
            NoteType::Public,
            client_2.rng(),
        )
        .unwrap();
    let note: InputNoteRecord =
        tx_request.expected_output_own_notes().pop().unwrap().clone().into();
    client_2.sync_state().await.unwrap();

    // Importing a public note before it's committed onchain should fail
    assert_eq!(
        client_2
            .import_notes(&[NoteFile::NoteId(note.id())])
            .await
            .unwrap_err()
            .to_string(),
        "note import error: No notes fetched from node".to_string()
    );
    execute_tx_and_sync(&mut client_1, faucet_account.id(), tx_request).await?;

    // Use client 1 to wait until a couple of blocks have passed
    wait_for_blocks(&mut client_1, 3).await;

    let new_sync_data = client_2.sync_state().await.unwrap();

    client_2.add_note_tag(note.metadata().unwrap().tag()).await.unwrap();
    client_2.import_notes(&[NoteFile::NoteId(note.clone().id())]).await.unwrap();
    client_2.sync_state().await.unwrap();
    let input_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    // If imported after execution and syncing then the inclusion proof should be Some
    assert!(input_note.inclusion_proof().is_some(), "Expected inclusion proof to be present");

    assert!(
        new_sync_data.block_num > input_note.inclusion_proof().unwrap().location().block_num() + 1
    );

    // If client 2 successfully consumes the note, we confirm we have MMR and block header data
    let tx_id =
        consume_notes(&mut client_2, client_2_account.id(), &[input_note.try_into().unwrap()])
            .await;
    wait_for_tx(&mut client_2, tx_id).await?;

    let tx_request = TransactionRequestBuilder::new()
        .build_mint_fungible_asset(
            FungibleAsset::new(faucet_account.id(), MINT_AMOUNT).unwrap(),
            first_basic_account.id(),
            NoteType::Private,
            client_2.rng(),
        )
        .unwrap();
    let note: InputNoteRecord =
        tx_request.expected_output_own_notes().pop().unwrap().clone().into();

    // Import the node before it's committed onchain works if we have full `NoteDetails`
    client_2.add_note_tag(note.metadata().unwrap().tag()).await.unwrap();
    client_2
        .import_notes(&[NoteFile::NoteDetails {
            details: note.clone().into(),
            after_block_num: client_1.get_sync_height().await.unwrap(),
            tag: Some(note.metadata().unwrap().tag()),
        }])
        .await
        .unwrap();
    let input_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();

    // If imported before execution, the note should be imported in `Expected` state
    assert!(matches!(input_note.state(), InputNoteState::Expected { .. }));

    execute_tx_and_sync(&mut client_1, faucet_account.id(), tx_request).await?;
    client_2.sync_state().await.unwrap();

    // After sync, the imported note should have inclusion proof even if it's not relevant for its
    // accounts.
    let input_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(input_note.inclusion_proof().is_some(), "Expected inclusion proof to be present");

    // If inclusion proof is invalid this should panic
    let tx_id =
        consume_notes(&mut client_1, first_basic_account.id(), &[input_note.try_into().unwrap()])
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;
    Ok(())
}

pub async fn test_import_expected_note_uncommitted(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator) = client_config.clone().into_client().await?;
    let faucet_account = insert_new_fungible_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await
    .unwrap()
    .0;

    let (mut client_2, _) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;
    let (client_2_account, _) = insert_new_wallet(
        &mut client_2,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    wait_for_node(&mut client_2).await;

    let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
        FungibleAsset::new(faucet_account.id(), MINT_AMOUNT).unwrap(),
        client_2_account.id(),
        NoteType::Public,
        client_1.rng(),
    )?;

    let note: InputNoteRecord =
        tx_request.expected_output_own_notes().pop().unwrap().clone().into();
    client_2.sync_state().await.unwrap();

    // If the verification is requested before execution then the import should fail
    let imported_note_id = client_2
        .import_notes(&[NoteFile::NoteDetails {
            details: note.into(),
            after_block_num: 0.into(),
            tag: None,
        }])
        .await?[0];

    let imported_note = client_2.get_input_note(imported_note_id).await.unwrap().unwrap();

    assert!(matches!(imported_note.state(), InputNoteState::Expected { .. }));
    Ok(())
}

pub async fn test_import_expected_notes_from_the_past_as_committed(
    client_config: ClientConfig,
) -> Result<()> {
    let (mut client_1, authenticator_1) = client_config.clone().into_client().await?;
    let (first_basic_account, faucet_account) = setup_wallet_and_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (mut client_2, _) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;

    wait_for_node(&mut client_2).await;

    let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
        FungibleAsset::new(faucet_account.id(), MINT_AMOUNT).unwrap(),
        first_basic_account.id(),
        NoteType::Public,
        client_1.rng(),
    )?;
    let note: InputNoteRecord =
        tx_request.expected_output_own_notes().pop().unwrap().clone().into();

    let block_height_before = client_1.get_sync_height().await.unwrap();

    execute_tx_and_sync(&mut client_1, faucet_account.id(), tx_request).await?;

    // importing the note before client_2 is synced will result in a note with `Expected` state
    let note_id = client_2
        .import_notes(&[NoteFile::NoteDetails {
            details: note.clone().into(),
            after_block_num: block_height_before,
            tag: Some(note.metadata().unwrap().tag()),
        }])
        .await?[0];

    let imported_note = client_2.get_input_note(note_id).await.unwrap().unwrap();

    assert!(matches!(imported_note.state(), InputNoteState::Expected { .. }));

    client_2.sync_state().await.unwrap();

    // Note already imported
    assert!(
        client_2
            .import_notes(&[NoteFile::NoteDetails {
                details: note.clone().into(),
                after_block_num: block_height_before,
                tag: Some(note.metadata().unwrap().tag()),
            }])
            .await?
            .is_empty()
    );

    let imported_note = client_2.get_input_note(note_id).await.unwrap().unwrap();

    // Get the note status in client 1
    let client_1_note = client_1.get_input_note(note_id).await.unwrap().unwrap();

    assert_eq!(imported_note.state(), client_1_note.state());
    assert!(matches!(imported_note.state(), InputNoteState::Committed { .. }));
    Ok(())
}

pub async fn test_get_account_update(client_config: ClientConfig) -> Result<()> {
    // Create a client with both public and private accounts.
    let (mut client, authenticator) = client_config.clone().into_client().await?;

    let (basic_wallet_1, faucet_account) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;
    wait_for_node(&mut client).await;

    let (basic_wallet_2, ..) = insert_new_wallet(
        &mut client,
        AccountStorageMode::Public,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    // Mint and consume notes with both accounts so they are included in the node.
    let tx_id_1 =
        mint_and_consume(&mut client, basic_wallet_1.id(), faucet_account.id(), NoteType::Private)
            .await;
    wait_for_tx(&mut client, tx_id_1).await?;
    let tx_id_2 =
        mint_and_consume(&mut client, basic_wallet_2.id(), faucet_account.id(), NoteType::Private)
            .await;
    wait_for_tx(&mut client, tx_id_2).await?;

    // Request updates from node for both accounts. The request should not fail and both types of
    // [`AccountDetails`] should be received.
    // TODO: should we expose the `get_account_update` endpoint from the Client?
    let rpc_api = client.test_rpc_api();
    let details1 = rpc_api.get_account_details(basic_wallet_1.id()).await.unwrap();
    let details2 = rpc_api.get_account_details(basic_wallet_2.id()).await.unwrap();

    assert!(matches!(details1, FetchedAccount::Private(_, _)));
    assert_matches!(details2, FetchedAccount::Public(account, _) if account.vault().get_balance(faucet_account.id()).unwrap() == MINT_AMOUNT);
    Ok(())
}

pub async fn test_sync_detail_values(client_config: ClientConfig) -> Result<()> {
    let (mut client1, authenticator_1) = client_config.clone().into_client().await?;
    let (mut client2, authenticator_2) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;
    wait_for_node(&mut client1).await;
    wait_for_node(&mut client2).await;

    let (first_regular_account, faucet_account_header) = setup_wallet_and_faucet(
        &mut client1,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (second_regular_account, ..) = insert_new_wallet(
        &mut client2,
        AccountStorageMode::Private,
        &authenticator_2,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let from_account_id = first_regular_account.id();
    let to_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    // First Mint necessary token
    let tx_id =
        mint_and_consume(&mut client1, from_account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client1, tx_id).await?;

    // Second client sync shouldn't have any new changes
    let new_details = client2.sync_state().await.unwrap();
    assert!(new_details.is_empty());

    // Do a transfer with recall from first account to second account
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();
    let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
        PaymentNoteDescription::new(vec![Asset::Fungible(asset)], from_account_id, to_account_id)
            .with_reclaim_height(new_details.block_num + 5),
        NoteType::Public,
        client1.rng(),
    )?;
    let note = tx_request.expected_output_own_notes().pop().unwrap();
    execute_tx_and_sync(&mut client1, from_account_id, tx_request).await?;

    // Second client sync should have new note
    let new_details = client2.sync_state().await.unwrap();
    assert_eq!(new_details.new_public_notes.len(), 1);
    assert_eq!(new_details.committed_notes.len(), 0);
    assert_eq!(new_details.consumed_notes.len(), 0);
    assert_eq!(new_details.updated_accounts.len(), 0);

    // Consume the note with the second account
    let tx_request = TransactionRequestBuilder::new().build_consume_notes(vec![note]).unwrap();
    execute_tx_and_sync(&mut client2, to_account_id, tx_request).await?;

    // First client sync should have a new nullifier as the note was consumed
    let new_details = client1.sync_state().await.unwrap();
    assert_eq!(new_details.committed_notes.len(), 0);
    assert_eq!(new_details.consumed_notes.len(), 1);
    Ok(())
}

/// This test runs 3 mint transactions that get included in different blocks so that once we sync
/// we can check that each transaction gets marked as committed in the corresponding block.
pub async fn test_multiple_transactions_can_be_committed_in_different_blocks_without_sync(
    client_config: ClientConfig,
) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;

    let (first_regular_account, faucet_account_header) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let from_account_id = first_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    // Mint first note
    let (first_note_id, first_note_tx_id) = {
        // Create a Mint Tx for 1000 units of our fungible asset
        let fungible_asset = FungibleAsset::new(faucet_account_id, MINT_AMOUNT).unwrap();

        info!(faucet_id = %faucet_account_id, target = %from_account_id, "Minting first asset");
        let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
            fungible_asset,
            from_account_id,
            NoteType::Private,
            client.rng(),
        )?;

        info!("Executing first mint transaction");
        let transaction_id =
            client.submit_new_transaction(faucet_account_id, tx_request.clone()).await?;
        let note_id = tx_request.expected_output_own_notes().pop().unwrap().id();

        (note_id, transaction_id)
    };

    // Mint second note
    let (second_note_id, second_note_tx_id) = {
        // Create a Mint Tx for 1000 units of our fungible asset
        let fungible_asset = FungibleAsset::new(faucet_account_id, MINT_AMOUNT).unwrap();

        info!(faucet_id = %faucet_account_id, target = %from_account_id, "Minting second asset");
        let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
            fungible_asset,
            from_account_id,
            NoteType::Private,
            client.rng(),
        )?;

        info!("Executing second mint transaction");
        let transaction_result =
            client.execute_transaction(faucet_account_id, tx_request.clone()).await.unwrap();
        let transaction_id = transaction_result.id();

        info!(tx_id = %transaction_id, "Sending second transaction to node");
        // May need a few attempts until it gets included
        let note_id = tx_request.expected_output_own_notes().pop().unwrap().id();
        while client
            .test_rpc_api()
            .get_notes_by_id(&[first_note_id])
            .await
            .unwrap()
            .is_empty()
        {
            std::thread::sleep(Duration::from_secs(3));
        }
        let proven_transaction = client.prove_transaction(&transaction_result).await.unwrap();
        let submission_height = client
            .submit_proven_transaction(proven_transaction, &transaction_result)
            .await
            .unwrap();
        client.apply_transaction(&transaction_result, submission_height).await.unwrap();

        (note_id, transaction_id)
    };

    // Mint third note
    let (third_note_id, third_note_tx_id) = {
        // Create a Mint Tx for 1000 units of our fungible asset
        let fungible_asset = FungibleAsset::new(faucet_account_id, MINT_AMOUNT).unwrap();

        info!(faucet_id = %faucet_account_id, target = %from_account_id, "Minting third asset");
        let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
            fungible_asset,
            from_account_id,
            NoteType::Private,
            client.rng(),
        )?;

        info!("Executing third mint transaction");
        let transaction_result =
            client.execute_transaction(faucet_account_id, tx_request.clone()).await.unwrap();
        let transaction_id = transaction_result.id();

        info!(tx_id = %transaction_id, "Sending third transaction to node");
        // May need a few attempts until it gets included
        let note_id = tx_request.expected_output_own_notes().pop().unwrap().id();
        while client
            .test_rpc_api()
            .get_notes_by_id(&[second_note_id])
            .await
            .unwrap()
            .is_empty()
        {
            std::thread::sleep(Duration::from_secs(3));
        }
        let proven_transaction = client.prove_transaction(&transaction_result).await.unwrap();
        let submission_height = client
            .submit_proven_transaction(proven_transaction, &transaction_result)
            .await
            .unwrap();
        client.apply_transaction(&transaction_result, submission_height).await.unwrap();

        (note_id, transaction_id)
    };

    // Wait until the note gets committed in the node (without syncing)
    while client
        .test_rpc_api()
        .get_notes_by_id(&[third_note_id])
        .await
        .unwrap()
        .is_empty()
    {
        std::thread::sleep(Duration::from_secs(3));
    }

    client.sync_state().await.unwrap();

    let all_transactions = client.get_transactions(TransactionFilter::All).await.unwrap();
    let first_tx = all_transactions.iter().find(|tx| tx.id == first_note_tx_id).unwrap();
    let second_tx = all_transactions.iter().find(|tx| tx.id == second_note_tx_id).unwrap();
    let third_tx = all_transactions.iter().find(|tx| tx.id == third_note_tx_id).unwrap();

    match (first_tx.status.clone(), second_tx.status.clone(), third_tx.status.clone()) {
        (
            TransactionStatus::Committed { block_number: first_tx_commit_height, .. },
            TransactionStatus::Committed {
                block_number: second_tx_commit_height, ..
            },
            TransactionStatus::Committed { block_number: third_tx_commit_height, .. },
        ) => {
            assert!(first_tx_commit_height < second_tx_commit_height);
            assert!(second_tx_commit_height < third_tx_commit_height);
        },
        _ => {
            panic!("All three TXs should be committed in different blocks")
        },
    }
    Ok(())
}

/// Test that checks multiple features:
/// - Consuming multiple notes in a single transaction.
/// - Consuming authenticated notes.
/// - Consuming unauthenticated notes.
pub async fn test_consume_multiple_expected_notes(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator_1) = client_config.clone().into_client().await?;
    let (mut unauth_client, authenticator_2) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;

    wait_for_node(&mut client).await;

    // Setup accounts
    let (target_basic_account_1, faucet_account_header) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;
    let (target_basic_account_2, ..) = insert_new_wallet(
        &mut unauth_client,
        AccountStorageMode::Private,
        &authenticator_2,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;
    unauth_client.sync_state().await.unwrap();

    let faucet_account_id = faucet_account_header.id();
    let to_account_ids = [target_basic_account_1.id(), target_basic_account_2.id()];

    let fungible_asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();

    // Mint tokens to the accounts
    let mint_tx_request = mint_multiple_fungible_asset(
        fungible_asset,
        &[to_account_ids[0], to_account_ids[0], to_account_ids[1], to_account_ids[1]],
        NoteType::Private,
        client.rng(),
    );
    let all_expected_notes = mint_tx_request.expected_output_own_notes();
    execute_tx_and_sync(&mut client, faucet_account_id, mint_tx_request).await?;

    unauth_client.sync_state().await.unwrap();

    // Filter notes by ownership
    let expected_notes = all_expected_notes.into_iter();
    let client_notes: Vec<_> = client.get_input_notes(NoteFilter::All).await.unwrap();
    let client_notes_ids: Vec<_> = client_notes.iter().map(|note| note.id()).collect();

    let (client_owned_notes, unauth_owned_notes): (Vec<_>, Vec<_>) =
        expected_notes.partition(|note| client_notes_ids.contains(&note.id()));

    // Create and execute transactions
    let tx_request_1 = TransactionRequestBuilder::new()
        .input_notes(client_owned_notes.iter().map(|note| (note.clone(), None)))
        .build()?;

    let tx_request_2 = TransactionRequestBuilder::new()
        .input_notes(unauth_owned_notes.iter().map(|note| ((*note).clone(), None)))
        .build()?;

    let tx_id_1 = client.submit_new_transaction(to_account_ids[0], tx_request_1).await.unwrap();
    let tx_id_2 = unauth_client
        .submit_new_transaction(to_account_ids[1], tx_request_2)
        .await
        .unwrap();

    // Ensure notes are processed
    assert!(!client.get_input_notes(NoteFilter::Processing).await.unwrap().is_empty());
    assert!(!unauth_client.get_input_notes(NoteFilter::Processing).await.unwrap().is_empty());

    wait_for_tx(&mut client, tx_id_1).await?;
    wait_for_tx(&mut unauth_client, tx_id_2).await?;

    // Verify no remaining expected notes and all notes are consumed
    assert!(client.get_input_notes(NoteFilter::Expected).await.unwrap().is_empty());
    assert!(unauth_client.get_input_notes(NoteFilter::Expected).await.unwrap().is_empty());

    assert!(
        !client.get_input_notes(NoteFilter::Consumed).await.unwrap().is_empty(),
        "Authenticated notes are consumed"
    );
    assert!(
        !unauth_client.get_input_notes(NoteFilter::Consumed).await.unwrap().is_empty(),
        "Unauthenticated notes are consumed"
    );

    // Validate the final asset amounts in each account
    for (client, account_id) in [(client, to_account_ids[0]), (unauth_client, to_account_ids[1])] {
        assert_account_has_single_asset(
            &client,
            account_id,
            faucet_account_id,
            TRANSFER_AMOUNT * 2,
        )
        .await;
    }
    Ok(())
}

pub async fn test_import_consumed_note_with_proof(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator_1) = client_config.clone().into_client().await?;
    let (first_regular_account, faucet_account_header) = setup_wallet_and_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (mut client_2, authenticator_2) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;
    let (client_2_account, _) = insert_new_wallet(
        &mut client_2,
        AccountStorageMode::Private,
        &authenticator_2,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    wait_for_node(&mut client_2).await;

    let from_account_id = first_regular_account.id();
    let to_account_id = client_2_account.id();
    let faucet_account_id = faucet_account_header.id();

    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    let current_block_num = client_1.get_sync_height().await.unwrap();
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();

    info!(from = %from_account_id, to = %to_account_id, "Running P2IDE transaction");
    let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
        PaymentNoteDescription::new(vec![Asset::Fungible(asset)], from_account_id, to_account_id)
            .with_reclaim_height(current_block_num),
        NoteType::Private,
        client_1.rng(),
    )?;
    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;
    let note = client_1
        .get_input_notes(NoteFilter::Committed)
        .await
        .unwrap()
        .first()
        .unwrap()
        .clone();

    // Consume the note with the sender account

    info!(note_id = %note.id(), account_id = %from_account_id, "Consuming note");
    let tx_request = TransactionRequestBuilder::new()
        .build_consume_notes(vec![note.clone().try_into().unwrap()])
        .unwrap();
    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;

    // Import the consumed note
    client_2
        .import_notes(&[NoteFile::NoteWithProof(
            note.clone().try_into().unwrap(),
            note.inclusion_proof().unwrap().clone(),
        )])
        .await?;

    let consumed_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(consumed_note.state(), InputNoteState::ConsumedExternal { .. }));
    Ok(())
}

pub async fn test_import_consumed_note_with_id(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator) = client_config.clone().into_client().await?;
    let (first_regular_account, second_regular_account, faucet_account_header) =
        setup_two_wallets_and_faucet(
            &mut client_1,
            AccountStorageMode::Private,
            &authenticator,
            RPO_FALCON_SCHEME_ID,
        )
        .await?;

    let (mut client_2, _) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;

    wait_for_node(&mut client_2).await;

    let from_account_id = first_regular_account.id();
    let to_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    let current_block_num = client_1.get_sync_height().await.unwrap();
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();

    info!(from = %from_account_id, to = %to_account_id, "Running P2IDE transaction (public)");
    let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
        PaymentNoteDescription::new(vec![Asset::Fungible(asset)], from_account_id, to_account_id)
            .with_reclaim_height(current_block_num),
        NoteType::Public,
        client_1.rng(),
    )?;
    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;
    let note = client_1
        .get_input_notes(NoteFilter::Committed)
        .await
        .unwrap()
        .first()
        .unwrap()
        .clone();

    // Consume the note with the sender account

    info!(note_id = %note.id(), account_id = %from_account_id, "Consuming note");
    let tx_request = TransactionRequestBuilder::new()
        .build_consume_notes(vec![note.clone().try_into().unwrap()])
        .unwrap();
    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;
    client_2.sync_state().await.unwrap();

    // Import the consumed note
    client_2.import_notes(&[NoteFile::NoteId(note.id())]).await.unwrap();

    let consumed_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(consumed_note.state(), InputNoteState::ConsumedExternal { .. }));
    Ok(())
}

pub async fn test_import_note_with_proof(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator) = client_config.clone().into_client().await?;
    let (first_regular_account, second_regular_account, faucet_account_header) =
        setup_two_wallets_and_faucet(
            &mut client_1,
            AccountStorageMode::Private,
            &authenticator,
            RPO_FALCON_SCHEME_ID,
        )
        .await?;

    let (mut client_2, _) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;

    wait_for_node(&mut client_2).await;

    let from_account_id = first_regular_account.id();
    let to_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    let current_block_num = client_1.get_sync_height().await.unwrap();
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();

    info!(from = %from_account_id, to = %to_account_id, "Running P2IDE transaction (with proof)");
    let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
        PaymentNoteDescription::new(vec![Asset::Fungible(asset)], from_account_id, to_account_id)
            .with_reclaim_height(current_block_num),
        NoteType::Private,
        client_1.rng(),
    )?;
    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;

    let note = client_1
        .get_input_notes(NoteFilter::Committed)
        .await
        .unwrap()
        .first()
        .unwrap()
        .clone();

    // Import the consumed note
    client_2
        .import_notes(&[NoteFile::NoteWithProof(
            note.clone().try_into().unwrap(),
            note.inclusion_proof().unwrap().clone(),
        )])
        .await?;

    let imported_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(imported_note.state(), InputNoteState::Unverified { .. }));

    client_2.sync_state().await.unwrap();
    let imported_note = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(imported_note.state(), InputNoteState::Committed { .. }));
    Ok(())
}

pub async fn test_discarded_transaction(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator_1) = client_config.clone().into_client().await?;
    let (first_regular_account, faucet_account_header) = setup_wallet_and_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator_1,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (mut client_2, authenticator_2) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;
    let (second_regular_account, ..) = insert_new_wallet(
        &mut client_2,
        AccountStorageMode::Private,
        &authenticator_2,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    wait_for_node(&mut client_2).await;

    let from_account_id = first_regular_account.id();
    let to_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    let current_block_num = client_1.get_sync_height().await.unwrap();
    let asset = FungibleAsset::new(faucet_account_id, TRANSFER_AMOUNT).unwrap();

    info!(from = %from_account_id, to = %to_account_id, "Running P2IDE transaction (discarded)");
    let tx_request = TransactionRequestBuilder::new().build_pay_to_id(
        PaymentNoteDescription::new(vec![Asset::Fungible(asset)], from_account_id, to_account_id)
            .with_reclaim_height(current_block_num),
        NoteType::Public,
        client_1.rng(),
    )?;

    execute_tx_and_sync(&mut client_1, from_account_id, tx_request).await?;
    client_2.sync_state().await.unwrap();
    let note = client_1
        .get_input_notes(NoteFilter::Committed)
        .await
        .unwrap()
        .first()
        .unwrap()
        .clone();

    info!(note_id = %note.id(), account_id = %from_account_id, "Consuming note (without submitting)");
    let tx_request = TransactionRequestBuilder::new()
        .build_consume_notes(vec![note.clone().try_into().unwrap()])
        .unwrap();

    // Consume the note in client 1 but dont submit it to the node
    let transaction_result =
        client_1.execute_transaction(from_account_id, tx_request.clone()).await.unwrap();
    let tx_id = transaction_result.id();

    // Store the account state before applying the transaction
    let account_hash_before_tx =
        client_1.account_reader(from_account_id).commitment().await.unwrap();

    // Apply the transaction
    let submission_height = client_1.get_sync_height().await.unwrap();
    client_1
        .apply_transaction(&transaction_result, submission_height)
        .await
        .unwrap();

    // Check that the account state has changed after applying the transaction
    let account_hash_after_tx =
        client_1.account_reader(from_account_id).commitment().await.unwrap();

    assert_ne!(
        account_hash_before_tx, account_hash_after_tx,
        "Account hash should change after applying the transaction"
    );

    let note_record = client_1.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(note_record.state(), InputNoteState::ProcessingAuthenticated(_)));

    // Consume the note in client 2
    execute_tx_and_sync(&mut client_2, to_account_id, tx_request).await?;

    let note_record = client_2.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(note_record.state(), InputNoteState::ConsumedAuthenticatedLocal(_)));

    // After sync the note in client 1 should be consumed externally and the transaction discarded
    client_1.sync_state().await.unwrap();
    let note_record = client_1.get_input_note(note.id()).await.unwrap().unwrap();
    assert!(matches!(note_record.state(), InputNoteState::ConsumedExternal(_)));
    let tx_record = client_1
        .get_transactions(TransactionFilter::All)
        .await
        .unwrap()
        .into_iter()
        .find(|tx| tx.id == tx_id)
        .with_context(|| {
            format!("Transaction with id {tx_id} not found in discarded transactions")
        })?;
    assert!(matches!(
        tx_record.status,
        TransactionStatus::Discarded(DiscardCause::InputConsumed)
    ));

    // Check that the account state has been rolled back after the transaction was discarded
    let account_hash_after_sync =
        client_1.account_reader(from_account_id).commitment().await.unwrap();

    assert_ne!(
        account_hash_after_sync, account_hash_after_tx,
        "Account hash should change after transaction was discarded"
    );
    assert_eq!(
        account_hash_after_sync, account_hash_before_tx,
        "Account hash should be rolled back to the value before the transaction"
    );
    Ok(())
}

struct AlwaysFailingProver;

impl AlwaysFailingProver {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait::async_trait]
impl TransactionProver for AlwaysFailingProver {
    async fn prove(
        &self,
        _inputs: TransactionInputs,
    ) -> Result<ProvenTransaction, TransactionProverError> {
        return Err(TransactionProverError::other("This prover always fails"));
    }
}

pub async fn test_custom_transaction_prover_error_caught(
    client_config: ClientConfig,
) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;
    let (first_regular_account, faucet_account_header) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let from_account_id = first_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    let fungible_asset = FungibleAsset::new(faucet_account_id, MINT_AMOUNT).unwrap();

    let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
        fungible_asset,
        from_account_id,
        NoteType::Private,
        client.rng(),
    )?;

    let transaction_result =
        client.execute_transaction(faucet_account_id, tx_request.clone()).await.unwrap();

    let result = client
        .prove_transaction_with(&transaction_result, Arc::new(AlwaysFailingProver::new()))
        .await;

    let Err(ClientError::TransactionProvingError(TransactionProverError::Other {
        error_msg, ..
    })) = result
    else {
        panic!("expected different prover error");
    };
    assert_eq!(error_msg.as_ref(), "This prover always fails");
    Ok(())
}

pub async fn test_locked_account(client_config: ClientConfig) -> Result<()> {
    let (mut client_1, authenticator) = client_config.clone().into_client().await?;

    let (faucet_account, _) = insert_new_fungible_faucet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (private_account, _) = insert_new_wallet(
        &mut client_1,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let from_account_id = private_account.id();
    let faucet_account_id = faucet_account.id();

    wait_for_node(&mut client_1).await;

    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    // Get full account from store for export to client_2
    let private_account: Account =
        client_1.get_account(from_account_id).await?.context("Account not found")?;

    let original_seed = private_account.seed();

    // Import private account in client 2
    let (mut client_2, _) = ClientConfig::default()
        .with_rpc_endpoint(client_config.rpc_endpoint())
        .into_client()
        .await?;
    client_2.add_account(&private_account, false).await.unwrap();

    wait_for_node(&mut client_2).await;

    // When imported the account shouldn't be locked
    assert!(!client_2.account_reader(from_account_id).status().await.unwrap().is_locked());

    // Consume note with private account in client 1
    let tx_id =
        mint_and_consume(&mut client_1, from_account_id, faucet_account_id, NoteType::Private)
            .await;
    wait_for_tx(&mut client_1, tx_id).await?;

    // After sync the private account should be locked in client 2
    let summary = client_2.sync_state().await.unwrap();
    assert!(summary.locked_accounts.contains(&from_account_id));
    let status = client_2.account_reader(from_account_id).status().await.unwrap();
    assert!(status.is_locked());
    assert_eq!(status.seed(), original_seed.as_ref());

    // Get updated account from client 1 and import it in client 2 with `overwrite` flag
    let updated_private_account: Account =
        client_1.get_account(from_account_id).await?.context("Account not found")?;
    client_2.add_account(&updated_private_account, true).await.unwrap();

    // After sync the private account shouldn't be locked in client 2
    client_2.sync_state().await.unwrap();
    assert!(!client_2.account_reader(from_account_id).status().await.unwrap().is_locked());
    Ok(())
}

pub async fn test_expired_transaction_fails(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;
    let (faucet_account, _) = insert_new_fungible_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let (private_account, ..) = insert_new_wallet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let from_account_id = private_account.id();
    let faucet_account_id = faucet_account.id();

    wait_for_node(&mut client).await;

    let expiration_delta = 2;

    // Create a Mint Tx for 1000 units of our fungible asset
    let fungible_asset = FungibleAsset::new(faucet_account_id, MINT_AMOUNT).unwrap();
    info!(faucet_id = %faucet_account_id, target = %from_account_id, expiration_delta, "Minting asset with expiration");
    let tx_request = TransactionRequestBuilder::new()
        .expiration_delta(expiration_delta)
        .build_mint_fungible_asset(
            fungible_asset,
            from_account_id,
            NoteType::Public,
            client.rng(),
        )?;

    info!("Executing transaction");
    let transaction_result =
        client.execute_transaction(faucet_account_id, tx_request).await.unwrap();

    info!(tx_id = %transaction_result.id(), "Transaction executed, waiting for expiration");
    wait_for_blocks(&mut client, (expiration_delta + 1).into()).await;

    info!("Sending expired transaction to node (expecting failure)");
    let proven_transaction = client.prove_transaction(&transaction_result).await.unwrap();
    let submitted_tx_result =
        match client.submit_proven_transaction(proven_transaction, &transaction_result).await {
            Ok(submission_height) => {
                client.apply_transaction(&transaction_result, submission_height).await
            },
            Err(err) => Err(err),
        };

    assert!(submitted_tx_result.is_err());
    Ok(())
}

/// Tests that RPC methods that are not directly related to the client logic
/// (like GetBlockByNumber) work correctly
pub async fn test_unused_rpc_api(client_config: ClientConfig) -> Result<()> {
    let (mut client, keystore) = client_config.into_client().await?;

    let (first_basic_account, faucet_account) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Public,
        &keystore,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    wait_for_node(&mut client).await;
    client.sync_state().await.unwrap();

    let first_block_num = client.get_sync_height().await.unwrap();

    let (block_header, _) = client
        .test_rpc_api()
        .get_block_header_by_number(Some(first_block_num), false)
        .await?;
    let block = client.test_rpc_api().get_block_by_number(first_block_num).await.unwrap();

    assert_eq!(&block_header, block.header());

    let (tx_id, note) =
        mint_note(&mut client, first_basic_account.id(), faucet_account.id(), NoteType::Public)
            .await;
    wait_for_tx(&mut client, tx_id).await?;

    let tx_id =
        consume_notes(&mut client, first_basic_account.id(), std::slice::from_ref(&note)).await;
    wait_for_tx(&mut client, tx_id).await?;

    // Define the account code for the custom library
    let custom_code = r#"
        use miden::protocol::native_account
        use miden::core::word

        const MAP_SLOT = word("miden::testing::client::map")

        pub proc update_map
            push.1.2.3.4
            # => [VALUE]
            push.0.0.0.0
            # => [KEY, VALUE]
            push.MAP_SLOT[0..2]
            exec.native_account::set_map_item
            dropw dropw dropw dropw
        end
    "#;

    let mut storage_map = StorageMap::new();
    storage_map.insert(
        StorageMapKey::new([Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)].into()),
        [Felt::new(1), Felt::new(0), Felt::new(0), Felt::new(0)].into(),
    )?;

    let map_slot_name =
        StorageSlotName::new("miden::testing::client::map").expect("slot name should be valid");
    let storage_slots = vec![StorageSlot::with_map(map_slot_name, storage_map)];
    let (account_with_map_item, _) = insert_account_with_custom_component(
        &mut client,
        custom_code,
        storage_slots,
        AccountStorageMode::Public,
        &keystore,
    )
    .await?;

    client.sync_state().await.unwrap();

    let tx_script = CodeBuilder::new()
        .with_linked_module("custom_library::set_map_item_library", custom_code)?
        .compile_tx_script(
            "
        use custom_library::set_map_item_library

        begin
             call.set_map_item_library::update_map
        end
        ",
        )?;

    let tx_request = TransactionRequestBuilder::new().custom_script(tx_script).build()?;
    execute_tx_and_sync(&mut client, account_with_map_item.id(), tx_request.clone()).await?;

    // Mint a new fungible asset to check account vault changes
    let faucet = insert_new_fungible_faucet(
        &mut client,
        AccountStorageMode::Private,
        &keystore,
        RPO_FALCON_SCHEME_ID,
    )
    .await?
    .0;

    let fungible_asset = FungibleAsset::new(faucet.id(), MINT_AMOUNT)?;
    let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
        fungible_asset,
        first_basic_account.id(),
        NoteType::Public,
        client.rng(),
    )?;
    let note = tx_request.expected_output_own_notes().pop().unwrap();
    execute_tx_and_sync(&mut client, fungible_asset.faucet_id(), tx_request.clone()).await?;

    let tx_request = TransactionRequestBuilder::new().build_consume_notes(vec![note.clone()])?;
    execute_tx_and_sync(&mut client, first_basic_account.id(), tx_request).await?;

    let nullifier = note.nullifier();

    let node_nullifier = client
        .test_rpc_api()
        .sync_nullifiers(&[nullifier.prefix()], 0.into(), None)
        .await
        .unwrap()
        .pop()
        .with_context(|| "no nullifier found in sync_nullifiers response")?;
    let node_nullifier_proof = client
        .test_rpc_api()
        .check_nullifiers(&[nullifier])
        .await
        .unwrap()
        .pop()
        .with_context(|| "no nullifier proof returned from check_nullifiers RPC API")?;
    let retrieved_note_script = client
        .test_rpc_api()
        .get_note_script_by_root(note.script().root())
        .await
        .unwrap();
    let sync_storage_maps = client
        .test_rpc_api()
        .sync_storage_maps(0.into(), None, account_with_map_item.id())
        .await
        .unwrap();
    let account_vault_info = client
        .test_rpc_api()
        .sync_account_vault(0.into(), None, first_basic_account.id())
        .await
        .unwrap();
    let transactions_info = client
        .test_rpc_api()
        .sync_transactions(0.into(), None, vec![first_basic_account.id()])
        .await
        .unwrap();

    assert_eq!(node_nullifier.nullifier, nullifier);
    assert_eq!(node_nullifier_proof.leaf().entries().first().unwrap().0, nullifier.as_word());
    assert_eq!(note.script().root(), retrieved_note_script.root());
    assert!(!sync_storage_maps.updates.is_empty());
    assert!(!account_vault_info.updates.is_empty());
    assert!(!transactions_info.transaction_records.is_empty());

    Ok(())
}

pub async fn test_ignore_invalid_notes(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;
    let (regular_account, second_regular_account, faucet_account_header) =
        setup_two_wallets_and_faucet(
            &mut client,
            AccountStorageMode::Private,
            &authenticator,
            RPO_FALCON_SCHEME_ID,
        )
        .await?;

    let account_id = regular_account.id();
    let second_account_id = second_regular_account.id();
    let faucet_account_id = faucet_account_header.id();

    // Mint 2 valid notes
    let (tx_id_1, note_1) =
        mint_note(&mut client, account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client, tx_id_1).await?;
    let (tx_id_2, note_2) =
        mint_note(&mut client, account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client, tx_id_2).await?;

    // Mint 2 invalid notes
    let (tx_id_3, note_3) =
        mint_note(&mut client, second_account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client, tx_id_3).await?;
    let (tx_id_4, note_4) =
        mint_note(&mut client, second_account_id, faucet_account_id, NoteType::Private).await;
    wait_for_tx(&mut client, tx_id_4).await?;

    // Create a transaction to consume all 4 notes but ignore the invalid ones
    let tx_request = TransactionRequestBuilder::new()
        .ignore_invalid_input_notes()
        .build_consume_notes(vec![
            note_1.clone(),
            note_3.clone(),
            note_2.clone(),
            note_4.clone(),
        ])?;

    execute_tx_and_sync(&mut client, account_id, tx_request).await?;

    // Check that only the valid notes were consumed
    let consumed_notes = client.get_input_notes(NoteFilter::Consumed).await.unwrap();
    assert_eq!(consumed_notes.len(), 2);
    assert!(consumed_notes.iter().any(|note| note.id() == note_1.id()));
    assert!(consumed_notes.iter().any(|note| note.id() == note_2.id()));
    Ok(())
}

pub async fn test_output_only_note(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;

    let faucet = insert_new_fungible_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await
    .unwrap()
    .0;

    let fungible_asset = FungibleAsset::new(faucet.id(), MINT_AMOUNT).unwrap();
    let tx_request = TransactionRequestBuilder::new().build_mint_fungible_asset(
        fungible_asset,
        AccountId::try_from(ACCOUNT_ID_REGULAR).unwrap(),
        NoteType::Public,
        client.rng(),
    )?;
    let note_id = tx_request.expected_output_own_notes().pop().unwrap().id();
    execute_tx_and_sync(&mut client, fungible_asset.faucet_id(), tx_request.clone()).await?;

    // The created note should be an output only note because it is not consumable by any client
    // account.
    let input_note = client.get_input_note(note_id).await.unwrap();
    assert!(input_note.is_none());

    let output_note = client.get_output_note(note_id).await.unwrap();
    assert!(output_note.is_some());
    Ok(())
}

/// Tests that `get_account_proof` with `AccountStorageRequirements` correctly filters storage
/// map entries by key.
///
/// Creates a public account with a map slot containing 2 entries, then verifies:
/// - Requesting with empty keys returns `AllEntries` with both entries.
/// - Requesting with one specific key returns `EntriesWithProofs` with just that entry's proof.
pub async fn test_get_account_storage_map_key_filtering(client_config: ClientConfig) -> Result<()> {
    let (mut client, keystore) = client_config.into_client().await?;
    wait_for_node(&mut client).await;

    let map_slot_name =
        StorageSlotName::new("miden::testing::client::map").expect("valid slot name");
    let map_key_1 =
        StorageMapKey::new([Felt::new(15), Felt::new(15), Felt::new(15), Felt::new(15)].into());
    let map_value_1 = Word::from([Felt::new(9), Felt::new(12), Felt::new(18), Felt::new(30)]);
    let map_key_2 =
        StorageMapKey::new([Felt::new(20), Felt::new(20), Felt::new(20), Felt::new(20)].into());
    let map_value_2 = Word::from([Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)]);

    let mut storage_map = StorageMap::new();
    storage_map.insert(map_key_1, map_value_1)?;
    storage_map.insert(map_key_2, map_value_2)?;

    let map_slot = StorageSlot::with_map(map_slot_name.clone(), storage_map);
    let component_code = CodeBuilder::default()
        .compile_component_code(
            "miden::testing::map_key_filtering",
            "pub proc dummy\n push.1\n end".to_string(),
        )
        .context("failed to compile component code")?;
    let component = AccountComponent::new(
        component_code,
        vec![map_slot],
        AccountComponentMetadata::new("miden::testing::map_key_filtering", AccountType::all()),
    )
    .map_err(|err| anyhow::anyhow!(err))?;

    let key_pair = AuthSecretKey::new_falcon512_poseidon2();
    let auth_component: AccountComponent =
        AuthSingleSig::new(key_pair.public_key().to_commitment(), AuthSchemeId::Falcon512Poseidon2)
            .into();

    let account = AccountBuilder::new(Default::default())
        .with_component(component)
        .with_auth_component(auth_component)
        .storage_mode(AccountStorageMode::Public)
        .build()
        .context("failed to build account")?;
    let account_id = account.id();

    keystore.add_key(&key_pair, account_id).await.context("failed to add key")?;
    client.add_account(&account, false).await?;

    // Deploy the account (first tx updates nonce)
    let tx_id = client
        .submit_new_transaction(account_id, TransactionRequestBuilder::new().build()?)
        .await?;
    wait_for_tx(&mut client, tx_id).await?;

    let rpc = client.test_rpc_api();

    // Request all entries (empty keys)
    let requirements_all = AccountStorageRequirements::new([(map_slot_name.clone(), [].iter())]);
    let (_, proof_all) = rpc
        .get_account_proof(account_id, requirements_all, AccountStateAt::ChainTip, None, None)
        .await?;
    let map_all = proof_all
        .find_map_details(&map_slot_name)
        .context("expected storage map details")?;

    assert!(
        matches!(map_all.entries, StorageMapEntries::AllEntries(ref e) if e.len() == 2),
        "expected AllEntries with 2 entries, got {:?}",
        map_all.entries,
    );

    // Request one specific key
    let requirements_one = AccountStorageRequirements::new([(map_slot_name.clone(), [&map_key_1])]);
    let (_, proof_one) = rpc
        .get_account_proof(account_id, requirements_one, AccountStateAt::ChainTip, None, None)
        .await?;
    let map_one = proof_one
        .find_map_details(&map_slot_name)
        .context("expected storage map details")?;

    match &map_one.entries {
        StorageMapEntries::EntriesWithProofs(proofs) => {
            assert_eq!(proofs.len(), 1, "expected 1 proof");
            let hashed_key = map_key_1.hash().as_word();
            let value = proofs[0].get(&hashed_key);
            assert!(value.is_some(), "proof should contain the requested key");
            assert_eq!(value.unwrap(), map_value_1, "value should match the requested key's value");
        },
        other => anyhow::bail!("expected EntriesWithProofs, got {:?}", other),
    }

    Ok(())
}

/// Tests that `get_account_proof` returns vault details based on the `known_vault_commitment`
/// parameter.
///
/// Creates a public faucet and wallet, mints tokens so the wallet holds assets,
/// then calls `get_account_proof` three times with different vault commitment values:
/// - `Some(EMPTY_WORD)`: always fetches vault data (commitment never matches).
/// - `Some(actual_root)`: commitment matches the node's state, so assets are empty.
/// - `None`: vault data not requested, so assets are empty.
pub async fn test_get_account_proof_returns_vault_details(
    client_config: ClientConfig,
) -> Result<()> {
    let (mut client, keystore) = client_config.into_client().await?;
    wait_for_node(&mut client).await;

    let (wallet, faucet) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Public,
        &keystore,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    // Mint tokens so the wallet has assets in its vault
    let tx_id = mint_and_consume(&mut client, wallet.id(), faucet.id(), NoteType::Public).await;
    wait_for_tx(&mut client, tx_id).await?;

    let rpc = client.test_rpc_api();

    // Query 1: Some(EMPTY_WORD) — always fetches vault data since EMPTY_WORD never matches
    let (_, proof) = rpc
        .get_account_proof(
            wallet.id(),
            AccountStorageRequirements::default(),
            AccountStateAt::ChainTip,
            None,
            Some(EMPTY_WORD),
        )
        .await?;

    let (_, details) = proof.into_parts();
    let details = details.context("expected account details for public account")?;
    let vault_root = details.header.vault_root();

    assert_eq!(
        details.vault_details.assets,
        vec![Asset::Fungible(FungibleAsset::new(faucet.id(), MINT_AMOUNT).unwrap())],
        "expected exactly 1 asset (the minted fungible token)"
    );

    // Query 2: Some(actual_root) — commitment matches, node returns empty assets
    let (_, proof) = rpc
        .get_account_proof(
            wallet.id(),
            AccountStorageRequirements::default(),
            AccountStateAt::ChainTip,
            None,
            Some(vault_root),
        )
        .await?;

    let (_, details) = proof.into_parts();
    let details = details.context("expected account details for public account")?;

    assert!(
        details.vault_details.assets.is_empty(),
        "expected empty assets when vault commitment matches"
    );

    // Query 3: None — vault data not requested, node returns empty assets
    let (_, proof) = rpc
        .get_account_proof(
            wallet.id(),
            AccountStorageRequirements::default(),
            AccountStateAt::ChainTip,
            None,
            None,
        )
        .await?;

    let (_, details) = proof.into_parts();
    let details = details.context("expected account details for public account")?;

    assert!(
        details.vault_details.assets.is_empty(),
        "expected empty assets when vault commitment is not requested"
    );

    Ok(())
}

/// Tests that pruning account history removes old committed states without affecting
/// the current account state. Sets up a faucet, mints twice to build up history,
/// then verifies that `prune_account_history` deletes intermediate states while
/// keeping the account readable and unchanged.
pub async fn test_prune_account_history(client_config: ClientConfig) -> Result<()> {
    let (mut client, authenticator) = client_config.into_client().await?;
    wait_for_node(&mut client).await;

    let (basic_account, faucet_account) = setup_wallet_and_faucet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    let faucet_id = faucet_account.id();
    let wallet_id = basic_account.id();

    // Mint twice: each mint advances the faucet nonce, creating historical entries.
    let (tx_id_1, _) = mint_note(&mut client, wallet_id, faucet_id, NoteType::Public).await;
    wait_for_tx(&mut client, tx_id_1).await?;

    let (tx_id_2, _) = mint_note(&mut client, wallet_id, faucet_id, NoteType::Public).await;
    wait_for_tx(&mut client, tx_id_2).await?;

    // Record faucet state before pruning.
    let faucet_before = client.get_account(faucet_id).await?.unwrap();

    // Prune faucet history up to nonce 1: should remove old committed states.
    let deleted = client.prune_account_history(faucet_id, Felt::new(1)).await?;
    assert!(deleted > 0, "Should have pruned old committed states");

    // Account should still be fully readable and unchanged.
    let faucet_after = client.get_account(faucet_id).await?.unwrap();
    assert_eq!(
        faucet_before.to_commitment(),
        faucet_after.to_commitment(),
        "Account state should be identical after pruning"
    );

    // Both accounts should still be readable.
    assert!(client.get_account(wallet_id).await?.is_some());
    assert!(client.get_account(faucet_id).await?.is_some());

    info!(deleted_single = deleted, "Prune account history test completed");

    Ok(())
}