miden-client 0.18.0

Client library that facilitates interaction with the Miden network
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
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use core::fmt::{self, Debug, Formatter};

use miden_protocol::account::{
    Account, AccountCode, AccountHeader, AccountId, AccountStorage, AccountStorageHeader,
    PartialAccount, PartialStorage, PartialStorageMap, StorageMap, StorageMapKey, StorageSlot,
    StorageSlotHeader, StorageSlotName, StorageSlotType,
};
use miden_protocol::asset::{Asset, AssetId, AssetVault, PartialVault};
use miden_protocol::block::account_tree::AccountWitness;
use miden_protocol::crypto::merkle::SparseMerklePath;
use miden_protocol::crypto::merkle::smt::PartialSmt;
use miden_protocol::transaction::AccountInputs;
use miden_objects::DecodeMessageExt;
use miden_protocol::{EMPTY_WORD, Word};
use miden_tx::utils::serde::{Deserializable, DeserializationError, Serializable};
use thiserror::Error;

use crate::alloc::string::ToString;
use crate::rpc::{AccountStateAt, RpcError};
use crate::rpc::domain::MissingFieldHelper;
use crate::rpc::generated::rpc::get_account_request::account_detail_request::storage_map_detail_request::{MapKeys, SlotData};
use crate::rpc::generated::rpc::get_account_request::account_detail_request::{
    StorageMapDetailRequest, StorageMapDetailRequests, StorageRequest, VaultAssetIds, VaultRequest,
};
use crate::rpc::generated::{self as proto};

// REGISTER ACCOUNT REQUEST
// ================================================================================================

/// Hides the invitation code, which is a secret that must not reach logs or error messages.
impl Debug for proto::rpc::RegisterAccountRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("RegisterAccountRequest")
            .field("account_id", &self.account_id)
            .finish_non_exhaustive()
    }
}

/// Hides the invitation code, which is a secret that must not reach logs or error messages.
impl Debug for proto::rpc::IsInvitationCodeValidRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("IsInvitationCodeValidRequest").finish_non_exhaustive()
    }
}

// FROM PROTO ACCOUNT HEADERS
// ================================================================================================

#[cfg(feature = "tonic")]
impl proto::rpc::get_account_response::AccountDetails {
    /// Converts the RPC response into `AccountDetails`.
    ///
    /// The RPC response may omit unchanged account codes. If so, this function uses
    /// `known_account_codes` to fill in the missing code. If a required code cannot be found in the
    /// response or `known_account_codes`, an error is returned.
    ///
    /// `fetch` specifies the requested storage keys and vault assets. The proofs must cover these
    /// keys and assets and verify against the account's roots.
    ///
    /// # Errors
    /// - If account code is missing both on `self` and `known_account_codes`
    /// - If data cannot be correctly deserialized
    /// - If a partial map does not cover exactly the keys requested for its slot
    /// - If the vault details do not answer `fetch` for the account's vault root
    pub fn into_domain(
        self,
        known_account_codes: &BTreeMap<Word, AccountCode>,
        fetch: &AccountFetch,
    ) -> Result<AccountDetails, crate::rpc::RpcError> {
        use crate::rpc::RpcError;
        use crate::rpc::domain::MissingFieldHelper;

        let proto::rpc::get_account_response::AccountDetails {
            header,
            storage_details,
            code,
            vault_details,
        } = self;
        let header: AccountHeader = header
            .ok_or(proto::rpc::get_account_response::AccountDetails::missing_field(stringify!(
                header
            )))?
            .decode_and_verify()?;

        let storage_details: AccountStorageDetails = storage_details
            .ok_or(proto::rpc::get_account_response::AccountDetails::missing_field(stringify!(
                storage_details
            )))?
            .try_into()?;

        storage_details.validate_against_request(fetch.storage())?;

        // If an account code was received, it means the previously known account code is no longer
        // valid. If it was not, it means we sent a code commitment that matched and so our code is
        // still valid
        let code = {
            let received_code: Option<AccountCode> =
                code.map(DecodeMessageExt::decode_and_verify).transpose()?;
            match received_code {
                Some(code) => code,
                None => known_account_codes
                    .get(&header.code_commitment())
                    .ok_or(RpcError::InvalidResponse(
                        "Account code was not provided, but the response did not contain it either"
                            .into(),
                    ))?
                    .clone(),
            }
        };

        let vault_details = AccountVaultDetails::try_from(
            vault_details
                .ok_or(proto::rpc::AccountVaultDetails::missing_field(stringify!(vault_details)))?,
        )?
        .validate_against_request(header.vault_root(), fetch.vault())?;

        Ok(AccountDetails {
            header,
            storage_details,
            code,
            vault_details,
        })
    }
}

// ACCOUNT DETAILS
// ================================================================================================

/// An account details.
#[derive(Clone, Debug)]
pub struct AccountDetails {
    pub header: AccountHeader,
    pub storage_details: AccountStorageDetails,
    pub code: AccountCode,
    pub vault_details: AccountVaultDetails,
}

impl TryFrom<AccountDetails> for PartialAccount {
    type Error = RpcError;

    /// Builds a partial account with the available vault and storage proofs.
    ///
    /// A map or vault that the node omitted or capped keeps its committed root. Reads fetch proofs
    /// for that root during execution.
    ///
    /// # Errors
    /// Returns an error if entries, assets, or proofs do not match the roots in the header, or if
    /// the account requires a seed.
    fn try_from(details: AccountDetails) -> Result<Self, Self::Error> {
        let AccountDetails {
            header,
            storage_details,
            code,
            vault_details,
        } = details;
        let mut storage_maps = Vec::with_capacity(storage_details.map_details.len());
        for map_details in storage_details.map_details {
            let map = match map_details.entries {
                StorageMapEntries::AllEntries(entries) => {
                    let map = StorageMap::with_entries(
                        entries.iter().map(|entry| (entry.key, entry.value)),
                    )
                    .map_err(|err| {
                        RpcError::InvalidResponse(format!("invalid storage map entries: {err}"))
                    })?;
                    let slot_root = storage_details
                        .header
                        .slots()
                        .find(|slot| *slot.name() == map_details.slot_name)
                        .map(StorageSlotHeader::value);
                    if Some(map.root()) != slot_root {
                        return Err(RpcError::InvalidResponse(format!(
                            "storage map entries for slot '{}' do not match the slot root",
                            map_details.slot_name
                        )));
                    }
                    PartialStorageMap::new_full(map)
                },
                StorageMapEntries::PartialMap { map_keys, partial_smt } => {
                    PartialStorageMap::try_from_parts(partial_smt, map_keys).map_err(|err| {
                        RpcError::InvalidResponse(format!("invalid storage map proof: {err}"))
                    })?
                },
                StorageMapEntries::LimitExceeded => continue,
            };
            storage_maps.push(map);
        }
        let vault = match vault_details {
            AccountVaultDetails::Assets(assets) => {
                let vault = AssetVault::new(&assets).map_err(|err| {
                    RpcError::InvalidResponse(format!("invalid asset list: {err}"))
                })?;
                if vault.root() == header.vault_root() {
                    PartialVault::new_full(vault)
                } else if assets.is_empty() {
                    // The node sends no assets when the request skips the vault or sends its
                    // current root.
                    PartialVault::new(header.vault_root())
                } else {
                    return Err(RpcError::InvalidResponse(
                        "asset list does not match the vault root".into(),
                    ));
                }
            },
            AccountVaultDetails::Partial(vault) => {
                if vault.root() != header.vault_root() {
                    return Err(RpcError::InvalidResponse(
                        "vault proofs do not match the vault root".into(),
                    ));
                }
                vault
            },
            AccountVaultDetails::TooManyAssets => PartialVault::new(header.vault_root()),
        };
        let storage = PartialStorage::new(storage_details.header, storage_maps)
            .map_err(|err| RpcError::InvalidResponse(format!("invalid partial storage: {err}")))?;
        let account = PartialAccount::new(header.id(), header.nonce(), code, storage, vault, None)
            .map_err(|err| RpcError::InvalidResponse(format!("invalid partial account: {err}")))?;
        if account.to_commitment() != header.to_commitment() {
            return Err(RpcError::InvalidResponse(
                "partial account does not match its header".into(),
            ));
        }
        Ok(account)
    }
}

impl TryFrom<&AccountDetails> for Account {
    type Error = RpcError;

    /// Builds an [`Account`] from [`AccountDetails`].
    ///
    /// This conversion fails if the account details are incomplete, i.e., when the account's
    /// storage maps or vault exceed the node's size threshold, or when only specific map keys or
    /// vault assets were requested.
    fn try_from(details: &AccountDetails) -> Result<Self, Self::Error> {
        let assets = match &details.vault_details {
            AccountVaultDetails::Assets(assets) => assets,
            AccountVaultDetails::TooManyAssets => {
                return Err(RpcError::ExpectedDataMissing(
                    "cannot build account: vault has too many assets".into(),
                ));
            },
            AccountVaultDetails::Partial(_) => {
                return Err(RpcError::ExpectedDataMissing(
                    "cannot build account: only specific vault assets were requested".into(),
                ));
            },
        };

        if let Some(slot_name) = details
            .storage_details
            .map_details
            .iter()
            .find(|m| m.is_limit_exceeded())
            .map(|m| &m.slot_name)
        {
            return Err(RpcError::ExpectedDataMissing(format!(
                "cannot build account: storage map slot '{slot_name}' has too many entries",
            )));
        }

        let mut slots: Vec<StorageSlot> = Vec::new();

        for slot_header in details.storage_details.header.slots() {
            match slot_header.slot_type() {
                StorageSlotType::Value => {
                    slots.push(StorageSlot::with_value(
                        slot_header.name().clone(),
                        slot_header.value(),
                    ));
                },
                StorageSlotType::Map => {
                    let map_details = details
                        .storage_details
                        .find_map_details(slot_header.name())
                        .ok_or_else(|| {
                            RpcError::ExpectedDataMissing(format!(
                                "slot '{}' is a map but has no map_details in response",
                                slot_header.name()
                            ))
                        })?;

                    let storage_map = map_details
                        .entries
                        .clone()
                        .into_storage_map()
                        .ok_or_else(|| {
                            RpcError::ExpectedDataMissing(format!(
                                "slot '{}' did not come back with all its entries, so the full \
                                 account cannot be built",
                                slot_header.name(),
                            ))
                        })?
                        .map_err(|err| {
                            RpcError::InvalidResponse(format!(
                                "the rpc api returned a non-valid map entry: {err}"
                            ))
                        })?;

                    slots.push(StorageSlot::with_map(slot_header.name().clone(), storage_map));
                },
            }
        }

        let asset_vault = AssetVault::new(assets).map_err(|err| {
            RpcError::InvalidResponse(format!("rpc api returned non-valid assets: {err}"))
        })?;

        let account_storage = AccountStorage::new(slots).map_err(|err| {
            RpcError::InvalidResponse(format!("rpc api returned non-valid storage slots: {err}"))
        })?;

        Account::new(
            details.header.id(),
            asset_vault,
            account_storage,
            details.code.clone(),
            details.header.nonce(),
            None,
        )
        .map_err(|err| {
            RpcError::InvalidResponse(format!(
                "failed to construct account from rpc api response: {err}"
            ))
        })
    }
}

// ACCOUNT STORAGE DETAILS
// ================================================================================================

/// Account storage details for `AccountResponse`
#[derive(Clone, Debug)]
pub struct AccountStorageDetails {
    /// Account storage header (storage slot info for up to 256 slots)
    pub header: AccountStorageHeader,
    /// Additional data for the requested storage maps
    pub map_details: Vec<AccountStorageMapDetails>,
}

impl AccountStorageDetails {
    /// Find the matching details for a map, given its storage slot name.
    //  This linear search should be good enough since there can be
    //  only up to 256 slots, so locality probably wins here.
    pub fn find_map_details(&self, target: &StorageSlotName) -> Option<&AccountStorageMapDetails> {
        self.map_details.iter().find(|map_detail| map_detail.slot_name == *target)
    }

    /// Checks that every partial map covers exactly the keys that were requested for its slot.
    ///
    /// # Errors
    /// - If a partial map does not cover a key that was requested for its slot.
    /// - If a partial map covers a key that was not requested.
    pub fn validate_against_request(&self, storage: &StorageMapFetch) -> Result<(), RpcError> {
        for map_detail in &self.map_details {
            let StorageMapEntries::PartialMap { map_keys, .. } = &map_detail.entries else {
                continue;
            };

            let requested_keys = match storage {
                StorageMapFetch::Slots(requirements) => {
                    requirements.keys_for_slot(&map_detail.slot_name)
                },
                StorageMapFetch::Skip | StorageMapFetch::All => &[],
            };
            if let Some(key) = requested_keys.iter().find(|key| !map_keys.contains(key)) {
                return Err(RpcError::InvalidResponse(format!(
                    "partial storage map for slot '{}' does not cover requested key {}",
                    map_detail.slot_name,
                    key.to_hex(),
                )));
            }
            if let Some(key) = map_keys.iter().find(|key| !requested_keys.contains(key)) {
                return Err(RpcError::InvalidResponse(format!(
                    "partial storage map for slot '{}' covers key {}, which was not requested",
                    map_detail.slot_name,
                    key.to_hex(),
                )));
            }
        }

        Ok(())
    }
}

impl TryFrom<proto::rpc::AccountStorageDetails> for AccountStorageDetails {
    type Error = RpcError;

    fn try_from(value: proto::rpc::AccountStorageDetails) -> Result<Self, Self::Error> {
        let header: AccountStorageHeader = value
            .header
            .ok_or(proto::account::AccountStorageHeader::missing_field(stringify!(header)))?
            .decode_and_verify()?;
        let map_details = value
            .map_details
            .into_iter()
            .map(core::convert::TryInto::try_into)
            .collect::<Result<Vec<AccountStorageMapDetails>, RpcError>>()?;

        // A partial map is only worth anything if it is anchored to the slot root the account
        // commitment covers. Without this check the node could serve a self-consistent tree of its
        // own making.
        for map_detail in &map_details {
            let StorageMapEntries::PartialMap { partial_smt, .. } = &map_detail.entries else {
                continue;
            };

            let slot = header
                .slots()
                .find(|slot| *slot.name() == map_detail.slot_name)
                .ok_or_else(|| {
                    RpcError::InvalidResponse(format!(
                        "partial storage map references slot '{}', which is absent from the \
                         storage header",
                        map_detail.slot_name,
                    ))
                })?;
            if slot.slot_type() != StorageSlotType::Map {
                return Err(RpcError::InvalidResponse(format!(
                    "partial storage map references slot '{}', which is not a map",
                    map_detail.slot_name,
                )));
            }
            if partial_smt.root() != slot.value() {
                return Err(RpcError::InvalidResponse(format!(
                    "partial storage map for slot '{}' has root {} but the storage header reports \
                     {}",
                    map_detail.slot_name,
                    partial_smt.root(),
                    slot.value(),
                )));
            }
        }

        Ok(Self { header, map_details })
    }
}

// ACCOUNT MAP DETAILS
// ================================================================================================

#[derive(Clone, Debug)]
pub struct AccountStorageMapDetails {
    /// Storage slot name of the storage map.
    pub slot_name: StorageSlotName,
    /// The map data the node returned for this slot. The variants are mutually exclusive.
    pub entries: StorageMapEntries,
}

impl AccountStorageMapDetails {
    /// The maximum number of keys the node will cover with a single partial map. The node counts
    /// this across all slots of a request, so honouring it per slot is a conservative bound.
    pub const MAX_PARTIAL_MAP_KEYS: usize = 64;

    /// Returns `true` when the node reported that this slot has more entries than it will return in
    /// a single response, meaning the entries have to be fetched through
    /// [`crate::rpc::NodeRpcClient::sync_storage_maps`] instead.
    pub fn is_limit_exceeded(&self) -> bool {
        matches!(self.entries, StorageMapEntries::LimitExceeded)
    }
}

impl TryFrom<proto::rpc::account_storage_details::AccountStorageMapDetails>
    for AccountStorageMapDetails
{
    type Error = RpcError;

    fn try_from(
        value: proto::rpc::account_storage_details::AccountStorageMapDetails,
    ) -> Result<Self, Self::Error> {
        use proto::rpc::account_storage_details::account_storage_map_details::Result as ProtoResult;

        let slot_name = StorageSlotName::new(value.slot_name)
            .map_err(|err| RpcError::ExpectedDataMissing(err.to_string()))?;

        let entries = match value.result {
            Some(ProtoResult::TooManyEntries(true)) => StorageMapEntries::LimitExceeded,
            Some(ProtoResult::TooManyEntries(false)) => {
                return Err(RpcError::InvalidResponse(
                    "too_many_entries must be true when set".into(),
                ));
            },
            Some(ProtoResult::AllEntries(all_entries)) => {
                let entries = all_entries
                    .entries
                    .into_iter()
                    .map(core::convert::TryInto::try_into)
                    .collect::<Result<Vec<StorageMapEntry>, RpcError>>()?;
                StorageMapEntries::AllEntries(entries)
            },
            Some(ProtoResult::PartialMap(partial_map)) => {
                if partial_map.map_keys.len() > Self::MAX_PARTIAL_MAP_KEYS {
                    return Err(RpcError::InvalidResponse(format!(
                        "partial storage map for slot '{slot_name}' contains {} keys, exceeding \
                         the limit of {}",
                        partial_map.map_keys.len(),
                        Self::MAX_PARTIAL_MAP_KEYS,
                    )));
                }

                let map_keys = partial_map
                    .map_keys
                    .into_iter()
                    .map(|key| Word::try_from(key).map(StorageMapKey::new))
                    .collect::<Result<Vec<_>, _>>()?;
                if let Some(key) = first_duplicate_key(&map_keys) {
                    return Err(RpcError::InvalidResponse(format!(
                        "partial storage map for slot '{slot_name}' repeats key {}",
                        key.to_hex(),
                    )));
                }

                let partial_smt: PartialSmt = partial_map
                        .partial_smt
                        .ok_or(proto::rpc::account_storage_details::account_storage_map_details::PartialStorageMap::missing_field(
                            stringify!(partial_smt),
                        ))?
                        .decode_and_verify()?;

                // The response sends the values only inside the tree, so a key the tree does not
                // track carries no value at all and would fail later, at read time.
                for key in &map_keys {
                    partial_smt.get_value(&key.hash().as_word()).map_err(|_| {
                        RpcError::InvalidResponse(format!(
                            "partial storage map for slot '{slot_name}' does not track key {}",
                            key.to_hex(),
                        ))
                    })?;
                }

                StorageMapEntries::PartialMap { map_keys, partial_smt }
            },
            None => {
                return Err(RpcError::InvalidResponse(format!(
                    "storage map details for slot '{slot_name}' carry no result",
                )));
            },
        };

        Ok(Self { slot_name, entries })
    }
}

/// Returns the first key that appears more than once, if any.
///
/// The key lists this guards are bounded by [`AccountStorageMapDetails::MAX_PARTIAL_MAP_KEYS`], so
/// the quadratic scan avoids allocating a set.
fn first_duplicate_key(keys: &[StorageMapKey]) -> Option<&StorageMapKey> {
    keys.iter()
        .enumerate()
        .find_map(|(index, key)| keys[..index].contains(key).then_some(key))
}

// STORAGE MAP ENTRY
// ================================================================================================

/// A storage map entry containing a key-value pair.
#[derive(Clone, Debug)]
pub struct StorageMapEntry {
    pub key: StorageMapKey,
    pub value: Word,
}

impl TryFrom<proto::rpc::account_storage_details::account_storage_map_details::all_map_entries::StorageMapEntry>
    for StorageMapEntry
{
    type Error = RpcError;

    fn try_from(value: proto::rpc::account_storage_details::account_storage_map_details::all_map_entries::StorageMapEntry) -> Result<Self, Self::Error> {
        let key = Word::try_from(value.key.ok_or(RpcError::ExpectedDataMissing("key".into()))?)
            .map(StorageMapKey::new)?;
        let value = value.value.ok_or(RpcError::ExpectedDataMissing("value".into()))?.try_into()?;
        Ok(Self { key, value })
    }
}

// STORAGE MAP ENTRIES
// ================================================================================================

/// The map data a `/GetAccount` response carries for one storage map slot. The variants are
/// mutually exclusive, mirroring the node's response.
#[derive(Clone, Debug)]
pub enum StorageMapEntries {
    /// The slot has more entries than the node returns in a single response. No entries are
    /// carried; fetch them with [`crate::rpc::NodeRpcClient::sync_storage_maps`].
    LimitExceeded,
    /// All entries in the storage map (no proofs needed as the full map is available).
    AllEntries(Vec<StorageMapEntry>),
    /// The specific keys that were requested, covered by a single partial SMT.
    ///
    /// The values are carried only inside `partial_smt`: read one by hashing its raw key and
    /// calling [`PartialSmt::get_value`]. Every key in `map_keys` is guaranteed to be tracked by
    /// `partial_smt`, so such a read cannot fail.
    PartialMap {
        /// The original, unhashed keys covered by `partial_smt`.
        map_keys: Vec<StorageMapKey>,
        /// The partial SMT proving the value of every key in `map_keys`.
        partial_smt: PartialSmt,
    },
}

impl StorageMapEntries {
    /// Converts the entries into a [`StorageMap`].
    ///
    /// Returns `None` for every variant other than [`AllEntries`](Self::AllEntries), since only
    /// that one carries the whole map.
    pub fn into_storage_map(
        self,
    ) -> Option<Result<StorageMap, miden_protocol::errors::StorageMapError>> {
        match self {
            StorageMapEntries::AllEntries(entries) => {
                Some(StorageMap::with_entries(entries.into_iter().map(|e| (e.key, e.value))))
            },
            StorageMapEntries::LimitExceeded | StorageMapEntries::PartialMap { .. } => None,
        }
    }
}

// ACCOUNT VAULT DETAILS
// ================================================================================================

/// The vault data that a `/GetAccount` response carries for an account. The variants are mutually
/// exclusive.
#[derive(Clone, Debug)]
pub enum AccountVaultDetails {
    /// The vault has more assets than the node returns in a single response. No assets are carried.
    /// Fetch them with [`crate::rpc::NodeRpcClient::sync_account_vault`].
    TooManyAssets,
    /// The assets in the account's vault.
    ///
    /// The list is empty if the request skips the vault, or if the vault root is equal to the
    /// commitment in [`VaultFetch::IfChangedFrom`]. Thus, an empty list does not show that the
    /// vault is empty.
    Assets(Vec<Asset>),
    /// Proofs for the assets requested with [`VaultFetch::Assets`]. The proofs also cover requested
    /// assets that are not in the vault.
    Partial(PartialVault),
}

impl AccountVaultDetails {
    /// Returns `true` if the vault has more assets than the node returns in a single response.
    pub fn is_too_many_assets(&self) -> bool {
        matches!(self, Self::TooManyAssets)
    }

    /// Returns the asset list, or `None` for every variant other than [`Assets`](Self::Assets).
    pub fn assets(&self) -> Option<&[Asset]> {
        match self {
            Self::Assets(assets) => Some(assets),
            Self::TooManyAssets | Self::Partial(_) => None,
        }
    }

    /// Converts the details into the vault proofs, or returns `None` for every variant other than
    /// [`Partial`](Self::Partial).
    pub fn into_partial_vault(self) -> Option<PartialVault> {
        match self {
            Self::Partial(partial_vault) => Some(partial_vault),
            Self::TooManyAssets | Self::Assets(_) => None,
        }
    }

    /// Checks the vault details against the request they answer and against `vault_root`, the vault
    /// root in the account header.
    ///
    /// The node can answer a [`VaultFetch::Assets`] request with the full vault contents instead of
    /// proofs. This function converts that answer into a partial vault. Thus, for an asset request,
    /// the result is always [`Partial`](Self::Partial).
    ///
    /// # Errors
    /// - If the details hold proofs for a request other than [`VaultFetch::Assets`]
    /// - If the vault has too many assets to answer a [`VaultFetch::Assets`] request
    /// - If the proofs or the full vault contents do not verify against `vault_root`
    /// - If the proofs do not cover all requested assets
    /// - If the proofs track an asset that was not requested
    #[cfg(feature = "tonic")]
    pub(crate) fn validate_against_request(
        self,
        vault_root: Word,
        vault_request: &VaultFetch,
    ) -> Result<Self, RpcError> {
        let VaultFetch::Assets(asset_ids) = vault_request else {
            if matches!(self, Self::Partial(_)) {
                return Err(RpcError::InvalidResponse(
                    "the response contains vault proofs that were not requested".into(),
                ));
            }
            return Ok(self);
        };

        let partial_vault = match self {
            Self::Partial(partial_vault) => {
                if let Some(asset_id) =
                    partial_vault.asset_ids().find(|asset_id| !asset_ids.contains(asset_id))
                {
                    return Err(RpcError::InvalidResponse(format!(
                        "the vault proofs track asset {asset_id}, which was not requested"
                    )));
                }
                partial_vault
            },
            Self::TooManyAssets => {
                return Err(RpcError::InvalidResponse(
                    "the node did not prove the requested assets because the vault is too large"
                        .into(),
                ));
            },
            Self::Assets(assets) => {
                PartialVault::new_full(AssetVault::new(&assets).map_err(|err| {
                    RpcError::InvalidResponse(format!("rpc api returned non-valid assets: {err}"))
                })?)
            },
        };

        if partial_vault.root() != vault_root {
            return Err(RpcError::InvalidResponse(format!(
                "the vault proofs verify against root {} but the account header has vault root \
                 {vault_root}",
                partial_vault.root(),
            )));
        }

        if let Some(asset_id) =
            asset_ids.iter().find(|asset_id| partial_vault.open(**asset_id).is_err())
        {
            return Err(RpcError::InvalidResponse(format!(
                "the vault proofs do not cover requested asset {asset_id}"
            )));
        }

        Ok(Self::Partial(partial_vault))
    }
}

impl TryFrom<proto::rpc::AccountVaultDetails> for AccountVaultDetails {
    type Error = RpcError;

    /// Converts the vault details of a `/GetAccount` response.
    ///
    /// The response must set only one of the asset list, the vault proofs, and the too many assets
    /// flag. A response that sets none of them converts to an empty asset list.
    fn try_from(value: proto::rpc::AccountVaultDetails) -> Result<Self, Self::Error> {
        let proto::rpc::AccountVaultDetails { too_many_assets, assets, partial_vault } = value;

        match (too_many_assets, assets.is_empty(), partial_vault) {
            (false, _, None) => Ok(Self::Assets(
                assets
                    .into_iter()
                    .map(DecodeMessageExt::decode_and_verify)
                    .collect::<Result<Vec<Asset>, _>>()?,
            )),
            (true, true, None) => Ok(Self::TooManyAssets),
            (false, true, Some(partial_vault)) => Ok(Self::Partial(partial_vault.try_into()?)),
            _ => Err(RpcError::InvalidResponse(
                "the vault details set more than one of the asset list, the vault proofs, and the \
                 too many assets flag"
                    .into(),
            )),
        }
    }
}

impl TryFrom<proto::rpc::account_vault_details::PartialVault> for PartialVault {
    type Error = RpcError;

    /// Converts the vault proofs of a `/GetAccount` response.
    ///
    /// [`PartialVault::try_from_parts`] rejects duplicate asset IDs and asset IDs that the partial
    /// SMT does not track.
    fn try_from(
        value: proto::rpc::account_vault_details::PartialVault,
    ) -> Result<Self, Self::Error> {
        let asset_ids = value
            .asset_ids
            .into_iter()
            .map(DecodeMessageExt::decode_and_verify)
            .collect::<Result<Vec<AssetId>, _>>()?;

        let partial_smt: PartialSmt = value
            .partial_smt
            .ok_or(proto::rpc::account_vault_details::PartialVault::missing_field(stringify!(
                partial_smt
            )))?
            .decode_and_verify()?;

        PartialVault::try_from_parts(partial_smt, asset_ids).map_err(|err| {
            RpcError::InvalidResponse(format!("rpc api returned a non-valid partial vault: {err}"))
        })
    }
}

// ACCOUNT PROOF
// ================================================================================================

/// Represents a proof of existence of an account's state at a specific block number.
#[derive(Clone, Debug)]
pub struct AccountProof {
    /// Account witness.
    account_witness: AccountWitness,
    /// State headers of public accounts.
    state_headers: Option<AccountDetails>,
}

impl AccountProof {
    /// Converts public account details and their witness into execution inputs.
    ///
    /// # Errors
    /// Returns an error if account details are absent or cannot form a partial account.
    pub fn into_account_inputs(self) -> Result<AccountInputs, RpcError> {
        let (witness, details) = self.into_parts();
        let details = details
            .ok_or_else(|| RpcError::ExpectedDataMissing("public account details".into()))?;
        Ok(AccountInputs::new(details.try_into()?, witness))
    }

    /// Creates a new [`AccountProof`].
    pub fn new(
        account_witness: AccountWitness,
        account_details: Option<AccountDetails>,
    ) -> Result<Self, AccountProofError> {
        if let Some(AccountDetails {
            header: account_header,
            storage_details: _,
            code,
            ..
        }) = &account_details
        {
            if account_header.to_commitment() != account_witness.state_commitment() {
                return Err(AccountProofError::InconsistentAccountCommitment);
            }
            if account_header.id() != account_witness.id() {
                return Err(AccountProofError::InconsistentAccountId);
            }
            if code.commitment() != account_header.code_commitment() {
                return Err(AccountProofError::InconsistentCodeCommitment);
            }
        }

        Ok(Self {
            account_witness,
            state_headers: account_details,
        })
    }

    /// Returns the account ID related to the account proof.
    pub fn account_id(&self) -> AccountId {
        self.account_witness.id()
    }

    /// Returns the account header, if present.
    pub fn account_header(&self) -> Option<&AccountHeader> {
        self.state_headers.as_ref().map(|account_details| &account_details.header)
    }

    /// Returns the storage header, if present.
    pub fn storage_header(&self) -> Option<&AccountStorageHeader> {
        self.state_headers
            .as_ref()
            .map(|account_details| &account_details.storage_details.header)
    }

    /// Returns the full storage details, if available (public accounts only).
    pub fn storage_details(&self) -> Option<&AccountStorageDetails> {
        self.state_headers.as_ref().map(|d| &d.storage_details)
    }

    /// Returns the vault details, if available (public accounts only).
    pub fn vault_details(&self) -> Option<&AccountVaultDetails> {
        self.state_headers.as_ref().map(|d| &d.vault_details)
    }

    /// Returns the storage map details for a specific slot, if available.
    pub fn find_map_details(
        &self,
        slot_name: &StorageSlotName,
    ) -> Option<&AccountStorageMapDetails> {
        self.state_headers
            .as_ref()
            .and_then(|details| details.storage_details.find_map_details(slot_name))
    }

    /// Returns the account code, if present.
    pub fn account_code(&self) -> Option<&AccountCode> {
        self.state_headers.as_ref().map(|headers| &headers.code)
    }

    /// Returns the code commitment, if account code is present in the state headers.
    pub fn code_commitment(&self) -> Option<Word> {
        self.account_code().map(AccountCode::commitment)
    }

    /// Returns the current state commitment of the account.
    pub fn account_commitment(&self) -> Word {
        self.account_witness.state_commitment()
    }

    pub fn account_witness(&self) -> &AccountWitness {
        &self.account_witness
    }

    /// Returns the proof of the account's inclusion.
    pub fn merkle_proof(&self) -> &SparseMerklePath {
        self.account_witness.path()
    }

    /// Deconstructs `AccountProof` into its individual parts.
    pub fn into_parts(self) -> (AccountWitness, Option<AccountDetails>) {
        (self.account_witness, self.state_headers)
    }

    /// Consumes the proof and returns the account details, if present (public accounts only).
    pub fn into_details(self) -> Option<AccountDetails> {
        self.state_headers
    }

    /// Mutable accessor for the account details, when present.
    ///
    /// Useful for resolving oversized vault or storage data in place via
    /// [`crate::rpc::NodeRpcClient::resolve_oversize_vault`] and
    /// [`crate::rpc::NodeRpcClient::resolve_oversize_storage_maps`].
    pub fn details_mut(&mut self) -> Option<&mut AccountDetails> {
        self.state_headers.as_mut()
    }
}

#[cfg(feature = "tonic")]
impl TryFrom<proto::rpc::GetAccountResponse> for AccountProof {
    type Error = RpcError;
    fn try_from(account_proof: proto::rpc::GetAccountResponse) -> Result<Self, Self::Error> {
        let Some(witness) = account_proof.witness else {
            return Err(RpcError::ExpectedDataMissing(
                "GetAccount returned an account without witness".to_string(),
            ));
        };

        let details: Option<AccountDetails> = {
            match account_proof.details {
                None => None,
                Some(details) => {
                    Some(details.into_domain(&BTreeMap::new(), &AccountFetch::default())?)
                },
            }
        };
        AccountProof::new(witness.decode_and_verify()?, details)
            .map_err(|err| RpcError::InvalidResponse(format!("{err}")))
    }
}

// ACCOUNT STORAGE REQUEST
// ================================================================================================

/// Per-slot map data to include in a `/GetAccount` response. Slots absent here are omitted from
/// `map_details` (the storage header still lists every slot).
///
/// - Empty key list: all entries, no proof. May come back as [`StorageMapEntries::LimitExceeded`].
/// - Non-empty key list: just those keys, covered by one partial SMT.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AccountStorageRequirements(BTreeMap<StorageSlotName, Vec<StorageMapKey>>);

impl AccountStorageRequirements {
    /// Requests the specified keys per slot, covered by one partial SMT per slot. An empty key
    /// iterator for a slot behaves like [`Self::all_entries`].
    ///
    /// Repeated keys within a slot are collapsed, since the node rejects a request that names the
    /// same key twice.
    pub fn new<'a>(
        slots_and_keys: impl IntoIterator<
            Item = (StorageSlotName, impl IntoIterator<Item = &'a StorageMapKey>),
        >,
    ) -> Self {
        let map = slots_and_keys
            .into_iter()
            .map(|(slot_name, keys_iter)| {
                let mut keys_vec: Vec<StorageMapKey> = Vec::new();
                for key in keys_iter {
                    if !keys_vec.contains(key) {
                        keys_vec.push(*key);
                    }
                }
                (slot_name, keys_vec)
            })
            .collect();

        AccountStorageRequirements(map)
    }

    /// Requests every entry of each given slot, without a proof. Oversize maps come back as
    /// [`StorageMapEntries::LimitExceeded`].
    pub fn all_entries(slot_names: &[StorageSlotName]) -> Self {
        AccountStorageRequirements(
            slot_names.iter().map(|name| (name.clone(), Vec::new())).collect(),
        )
    }

    pub fn inner(&self) -> &BTreeMap<StorageSlotName, Vec<StorageMapKey>> {
        &self.0
    }

    /// Returns the keys requested for a given slot, or an empty slice if none were specified.
    pub fn keys_for_slot(&self, slot_name: &StorageSlotName) -> &[StorageMapKey] {
        self.0.get(slot_name).map_or(&[], Vec::as_slice)
    }
}

impl From<AccountStorageRequirements> for Vec<StorageMapDetailRequest> {
    fn from(value: AccountStorageRequirements) -> Vec<StorageMapDetailRequest> {
        let request_map = value.0;
        let mut requests = Vec::with_capacity(request_map.len());
        for (slot_name, map_keys) in request_map {
            let slot_data = if map_keys.is_empty() {
                Some(SlotData::AllEntries(true))
            } else {
                let keys = map_keys.into_iter().map(|key| Word::from(key).into()).collect();
                Some(SlotData::MapKeys(MapKeys { map_keys: keys }))
            };
            requests.push(StorageMapDetailRequest {
                slot_name: slot_name.to_string(),
                slot_data,
            });
        }
        requests
    }
}

impl Serializable for AccountStorageRequirements {
    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
        target.write(&self.0);
    }
}

impl Deserializable for AccountStorageRequirements {
    fn read_from<R: miden_tx::utils::serde::ByteReader>(
        source: &mut R,
    ) -> Result<Self, miden_tx::utils::serde::DeserializationError> {
        Ok(AccountStorageRequirements(source.read()?))
    }
}

// GET ACCOUNT REQUEST
// ================================================================================================

/// Controls whether vault data is included in a `/GetAccount` response.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum VaultFetch {
    /// Do not include vault data in the response.
    #[default]
    Skip,
    /// Always include vault data in the response.
    Always,
    /// Include vault data only if the account's current vault root differs from this commitment.
    ///
    /// An omitted asset list is byte-identical to a genuinely empty vault, so callers must keep the
    /// vault whose root they send and verify any reconstruction against the header's vault root.
    IfChangedFrom(Word),
    /// Include proofs for these assets only, in [`AccountVaultDetails::Partial`]. The node proves
    /// an asset that is not in the vault as absent.
    ///
    /// The node accepts at most
    /// [`RpcLimits::vault_assets_limit`](crate::rpc::RpcLimits::vault_assets_limit) assets in a
    /// single request.
    Assets(BTreeSet<AssetId>),
}

impl Serializable for VaultFetch {
    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
        match self {
            Self::Skip => target.write_u8(0),
            Self::Always => target.write_u8(1),
            Self::IfChangedFrom(root) => {
                target.write_u8(2);
                target.write(root);
            },
            Self::Assets(asset_ids) => {
                target.write_u8(3);
                target.write(asset_ids);
            },
        }
    }
}

impl Deserializable for VaultFetch {
    fn read_from<R: miden_tx::utils::serde::ByteReader>(
        source: &mut R,
    ) -> Result<Self, DeserializationError> {
        match source.read_u8()? {
            0 => Ok(Self::Skip),
            1 => Ok(Self::Always),
            2 => Ok(Self::IfChangedFrom(source.read()?)),
            3 => Ok(Self::Assets(source.read()?)),
            tag => Err(DeserializationError::InvalidValue(format!(
                "invalid vault requirements tag: {tag}"
            ))),
        }
    }
}

impl From<VaultFetch> for Option<VaultRequest> {
    /// Encodes the policy as the request's `vault_request`: `None` skips the vault, the empty word
    /// (which no real vault root equals) always fetches it, a concrete commitment fetches it only
    /// when it differs, and a set of asset IDs requests proofs for those assets.
    fn from(vault: VaultFetch) -> Self {
        let commitment = match vault {
            VaultFetch::Skip => return None,
            VaultFetch::Always => EMPTY_WORD,
            VaultFetch::IfChangedFrom(commitment) => commitment,
            VaultFetch::Assets(asset_ids) => {
                return Some(VaultRequest::AssetIds(VaultAssetIds {
                    asset_ids: asset_ids.into_iter().map(Into::into).collect(),
                }));
            },
        };
        Some(VaultRequest::AssetVaultCommitment(commitment.into()))
    }
}

/// Which storage map entries to include in a `/GetAccount` response.
///
/// Mirrors the node's `AccountDetailRequest` storage request: the storage header (slot roots) is
/// always returned; this only controls which map *entries* come with it. The variants are mutually
/// exclusive.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum StorageMapFetch {
    /// Don't request any map entries; only the storage header is returned.
    #[default]
    Skip,
    /// Request entries for every storage map slot, without naming the slots in advance. Oversize
    /// maps come back as [`StorageMapEntries::LimitExceeded`], to be resolved via
    /// [`crate::rpc::NodeRpcClient::sync_storage_maps`].
    All,
    /// Request entries only for the explicitly named slots. See [`AccountStorageRequirements`] for
    /// the per-slot semantics.
    Slots(AccountStorageRequirements),
}

impl Serializable for StorageMapFetch {
    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
        match self {
            Self::Skip => target.write_u8(0),
            Self::All => target.write_u8(1),
            Self::Slots(requirements) => {
                target.write_u8(2);
                target.write(requirements);
            },
        }
    }
}

impl Deserializable for StorageMapFetch {
    fn read_from<R: miden_tx::utils::serde::ByteReader>(
        source: &mut R,
    ) -> Result<Self, DeserializationError> {
        match source.read_u8()? {
            0 => Ok(Self::Skip),
            1 => Ok(Self::All),
            2 => Ok(Self::Slots(source.read()?)),
            tag => Err(DeserializationError::InvalidValue(format!(
                "invalid storage map fetch tag: {tag}"
            ))),
        }
    }
}

impl From<StorageMapFetch> for Option<StorageRequest> {
    fn from(storage: StorageMapFetch) -> Self {
        match storage {
            StorageMapFetch::Skip => None,
            StorageMapFetch::All => Some(StorageRequest::AllStorageMaps(true)),
            StorageMapFetch::Slots(reqs) => {
                Some(StorageRequest::StorageMaps(StorageMapDetailRequests {
                    storage_maps: reqs.into(),
                }))
            },
        }
    }
}

/// Storage map entries and vault data to fetch for an account.
///
/// Both policies default to `Skip`. A transaction reads skipped entries and assets during
/// execution, one lookup at a time, from the store or from the node.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AccountFetch {
    storage: StorageMapFetch,
    vault: VaultFetch,
}

impl AccountFetch {
    /// Creates a fetch policy that skips storage map entries and vault data.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets which storage map entries to fetch.
    #[must_use]
    pub fn with_storage(mut self, storage: StorageMapFetch) -> Self {
        self.storage = storage;
        self
    }

    /// Sets which vault data to fetch.
    #[must_use]
    pub fn with_vault(mut self, vault: VaultFetch) -> Self {
        self.vault = vault;
        self
    }

    /// Returns the storage map fetch policy.
    pub fn storage(&self) -> &StorageMapFetch {
        &self.storage
    }

    /// Returns the vault fetch policy.
    pub fn vault(&self) -> &VaultFetch {
        &self.vault
    }
}

impl Serializable for AccountFetch {
    fn write_into<W: miden_tx::utils::serde::ByteWriter>(&self, target: &mut W) {
        target.write(&self.storage);
        target.write(&self.vault);
    }
}

impl Deserializable for AccountFetch {
    fn read_from<R: miden_tx::utils::serde::ByteReader>(
        source: &mut R,
    ) -> Result<Self, DeserializationError> {
        Ok(Self {
            storage: source.read()?,
            vault: source.read()?,
        })
    }
}

/// Parameters for [`crate::rpc::NodeRpcClient::get_account`].
///
/// The node returns details for public accounts only. For a private account, the response holds the
/// witness alone, and `fetch` and `known_code` have no effect.
#[derive(Clone, Debug)]
pub struct GetAccountRequest {
    /// Account to fetch.
    pub account_id: AccountId,
    /// Storage map entries and vault data to include in the response.
    pub fetch: AccountFetch,
    /// Block at which to retrieve the proof.
    pub at: AccountStateAt,
    /// Code the client already has. The node omits code with the same commitment.
    pub known_code: Option<AccountCode>,
}

impl GetAccountRequest {
    /// Creates a request at the chain tip with no map entries, known code, or vault data.
    #[must_use]
    pub fn new(account_id: AccountId) -> Self {
        Self {
            account_id,
            fetch: AccountFetch::default(),
            at: AccountStateAt::ChainTip,
            known_code: None,
        }
    }

    /// Sets the storage map entries and vault data to include in the response.
    #[must_use]
    pub fn with_fetch(mut self, fetch: AccountFetch) -> Self {
        self.fetch = fetch;
        self
    }

    /// Sets the target block for this request.
    #[must_use]
    pub fn at(mut self, at: AccountStateAt) -> Self {
        self.at = at;
        self
    }

    /// Provides the code commitment the client already holds, so the node can skip re-sending
    /// matching code.
    #[must_use]
    pub fn with_known_code(mut self, known_code: Option<AccountCode>) -> Self {
        self.known_code = known_code;
        self
    }
}

// ERRORS
// ================================================================================================

#[derive(Debug, Error)]
pub enum AccountProofError {
    #[error(
        "the received account commitment doesn't match the received account header's commitment"
    )]
    InconsistentAccountCommitment,
    #[error("the received account id doesn't match the received account header's id")]
    InconsistentAccountId,
    #[error(
        "the received code commitment doesn't match the received account header's code commitment"
    )]
    InconsistentCodeCommitment,
}

#[cfg(test)]
mod tests {
    use miden_protocol::Word;
    use miden_protocol::account::{StorageMapKey, StorageSlotName};
    use miden_protocol::asset::AssetId;
    use miden_protocol::testing::account_id::ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET;
    use miden_tx::utils::serde::{Deserializable, Serializable};

    use super::{AccountFetch, AccountStorageRequirements, StorageMapFetch, VaultFetch, proto};
    use crate::alloc::string::ToString;

    #[test]
    fn invitation_code_validation_request_debug_hides_code() {
        let code = "secret-invitation-code";
        let request =
            proto::rpc::IsInvitationCodeValidRequest { invitation_code: code.to_string() };

        let debug = format!("{request:?}");
        assert!(debug.contains("IsInvitationCodeValidRequest"));
        assert!(!debug.contains(code));
    }

    #[test]
    fn account_fetch_roundtrip() {
        let slot = StorageSlotName::new("miden::testing::map").unwrap();
        let key = StorageMapKey::new(Word::from([1u32; 4]));
        let storage = AccountStorageRequirements::new([(slot, &[key])]);
        let asset_id = AssetId::new_fungible(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET.try_into().unwrap());

        for storage in
            [StorageMapFetch::Skip, StorageMapFetch::All, StorageMapFetch::Slots(storage)]
        {
            let fetch = AccountFetch::new().with_storage(storage);
            for fetch in [
                fetch.clone(),
                fetch.clone().with_vault(VaultFetch::Skip),
                fetch.clone().with_vault(VaultFetch::Always),
                fetch.clone().with_vault(VaultFetch::IfChangedFrom(Word::from([2u32; 4]))),
                fetch.with_vault(VaultFetch::Assets([asset_id].into())),
            ] {
                let decoded = AccountFetch::read_from_bytes(&fetch.to_bytes()).unwrap();
                assert_eq!(decoded, fetch);
            }
        }
    }
}

#[cfg(all(test, feature = "testing", feature = "tonic"))]
mod vault_details_tests {
    use alloc::collections::BTreeSet;
    use alloc::vec::Vec;

    use miden_protocol::account::AccountId;
    use miden_protocol::asset::{Asset, AssetId, AssetVault, FungibleAsset, PartialVault};
    use miden_protocol::testing::account_id::{
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    };

    use super::{AccountVaultDetails, VaultAssetIds, VaultFetch, VaultRequest, proto};

    /// Returns a vault that holds one asset, that asset, and the ID of an asset that is not in the
    /// vault.
    fn vault_with_one_asset() -> (AssetVault, Asset, AssetId) {
        let held_faucet = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();
        let absent_faucet = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).unwrap();
        let asset: Asset = FungibleAsset::new(held_faucet, 100).unwrap().into();
        let vault = AssetVault::new(&[asset]).unwrap();
        (vault, asset, AssetId::new_fungible(absent_faucet))
    }

    /// Returns the proofs of `asset_ids` in `vault`.
    fn partial_vault(vault: &AssetVault, asset_ids: &[AssetId]) -> PartialVault {
        PartialVault::with_witnesses(asset_ids.iter().map(|asset_id| vault.open(*asset_id)))
            .unwrap()
    }

    /// Returns vault details that hold the proofs of `asset_ids` in `vault`.
    fn proof_details(vault: &AssetVault, asset_ids: &[AssetId]) -> AccountVaultDetails {
        AccountVaultDetails::Partial(partial_vault(vault, asset_ids))
    }

    fn asset_request(asset_ids: &[AssetId]) -> VaultFetch {
        VaultFetch::Assets(asset_ids.iter().copied().collect())
    }

    #[test]
    fn asset_request_encodes_the_asset_ids() {
        let (_, asset, absent) = vault_with_one_asset();
        let asset_ids = BTreeSet::from([asset.id(), absent]);

        let request: Option<VaultRequest> = VaultFetch::Assets(asset_ids.clone()).into();

        let expected = asset_ids.into_iter().map(Into::into).collect();
        assert_eq!(request, Some(VaultRequest::AssetIds(VaultAssetIds { asset_ids: expected })));
    }

    #[test]
    fn proofs_that_cover_the_request_are_accepted() {
        let (vault, asset, absent) = vault_with_one_asset();
        let request = asset_request(&[asset.id(), absent]);

        let details = proof_details(&vault, &[asset.id(), absent])
            .validate_against_request(vault.root(), &request)
            .unwrap();

        let partial_vault = details.into_partial_vault().expect("expected vault proofs");
        assert_eq!(partial_vault.get(asset.id()).unwrap(), Some(asset));
        assert_eq!(partial_vault.get(absent).unwrap(), None);
    }

    #[test]
    fn proofs_against_another_root_are_rejected() {
        let (vault, asset, _) = vault_with_one_asset();
        let other_root = AssetVault::default().root();

        let result = proof_details(&vault, &[asset.id()])
            .validate_against_request(other_root, &asset_request(&[asset.id()]));

        assert!(result.is_err());
    }

    /// The vault holds a second asset, so the proof of the first asset does not cover it. With one
    /// asset only, its proof would also prove the absence of every other asset.
    #[test]
    fn proofs_that_miss_a_requested_asset_are_rejected() {
        let (_, asset, _) = vault_with_one_asset();
        let other_faucet = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).unwrap();
        let other_asset: Asset = FungibleAsset::new(other_faucet, 5).unwrap().into();
        let vault = AssetVault::new(&[asset, other_asset]).unwrap();

        let result = proof_details(&vault, &[asset.id()]).validate_against_request(
            vault.root(),
            &asset_request(&[asset.id(), other_asset.id()]),
        );

        assert!(result.is_err());
    }

    #[test]
    fn proofs_that_were_not_requested_are_rejected() {
        let (vault, asset, _) = vault_with_one_asset();

        let result = proof_details(&vault, &[asset.id()])
            .validate_against_request(vault.root(), &VaultFetch::Always);

        assert!(result.is_err());
    }

    /// The node can send the full vault contents instead of proofs. The client converts that answer
    /// into proofs, so the callers handle only one shape.
    #[test]
    fn full_vault_answer_is_converted_to_proofs() {
        let (vault, asset, absent) = vault_with_one_asset();
        let details = AccountVaultDetails::Assets(vec![asset])
            .validate_against_request(vault.root(), &asset_request(&[asset.id(), absent]))
            .unwrap();

        let partial_vault = details.into_partial_vault().expect("expected vault proofs");
        assert_eq!(partial_vault.get(asset.id()).unwrap(), Some(asset));
        assert_eq!(partial_vault.get(absent).unwrap(), None);
    }

    #[test]
    fn too_many_assets_answer_to_an_asset_request_is_rejected() {
        let (vault, asset, _) = vault_with_one_asset();
        let result = AccountVaultDetails::TooManyAssets
            .validate_against_request(vault.root(), &asset_request(&[asset.id()]));

        assert!(result.is_err());
    }

    #[test]
    fn partial_vault_round_trips_through_proto() {
        let (vault, asset, absent) = vault_with_one_asset();
        let expected = partial_vault(&vault, &[asset.id(), absent]);
        let response = proto::rpc::AccountVaultDetails {
            too_many_assets: false,
            assets: Vec::new(),
            partial_vault: Some(proto::rpc::account_vault_details::PartialVault {
                asset_ids: vec![asset.id().into(), absent.into()],
                partial_smt: Some(expected.partial_smt().clone().into()),
            }),
        };

        let details = AccountVaultDetails::try_from(response).unwrap();

        assert_eq!(details.into_partial_vault(), Some(expected));
    }

    #[test]
    fn partial_vault_with_an_asset_list_is_rejected() {
        let (vault, asset, _) = vault_with_one_asset();
        let partial_vault = partial_vault(&vault, &[asset.id()]);
        let response = proto::rpc::AccountVaultDetails {
            too_many_assets: false,
            assets: vec![asset.into()],
            partial_vault: Some(proto::rpc::account_vault_details::PartialVault {
                asset_ids: vec![asset.id().into()],
                partial_smt: Some(partial_vault.partial_smt().clone().into()),
            }),
        };

        assert!(AccountVaultDetails::try_from(response).is_err());
    }

    #[test]
    fn too_many_assets_flag_converts_to_its_variant() {
        let response = proto::rpc::AccountVaultDetails {
            too_many_assets: true,
            assets: Vec::new(),
            partial_vault: None,
        };

        let details = AccountVaultDetails::try_from(response).unwrap();

        assert!(details.is_too_many_assets());
    }

    #[test]
    fn too_many_assets_flag_with_an_asset_list_is_rejected() {
        let (_, asset, _) = vault_with_one_asset();
        let response = proto::rpc::AccountVaultDetails {
            too_many_assets: true,
            assets: vec![asset.into()],
            partial_vault: None,
        };

        assert!(AccountVaultDetails::try_from(response).is_err());
    }

    #[test]
    fn partial_vault_with_the_too_many_assets_flag_is_rejected() {
        let (vault, asset, _) = vault_with_one_asset();
        let partial_vault = partial_vault(&vault, &[asset.id()]);
        let response = proto::rpc::AccountVaultDetails {
            too_many_assets: true,
            assets: Vec::new(),
            partial_vault: Some(proto::rpc::account_vault_details::PartialVault {
                asset_ids: vec![asset.id().into()],
                partial_smt: Some(partial_vault.partial_smt().clone().into()),
            }),
        };

        assert!(AccountVaultDetails::try_from(response).is_err());
    }

    #[test]
    fn proofs_that_track_an_asset_that_was_not_requested_are_rejected() {
        let (_, asset, _) = vault_with_one_asset();
        let other_faucet = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).unwrap();
        let other_asset: Asset = FungibleAsset::new(other_faucet, 5).unwrap().into();
        let vault = AssetVault::new(&[asset, other_asset]).unwrap();

        let result = proof_details(&vault, &[asset.id(), other_asset.id()])
            .validate_against_request(vault.root(), &asset_request(&[asset.id()]));

        assert!(result.is_err());
    }
}