namada_wallet 0.251.4

Namada wallet library code
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
#![allow(clippy::print_stdout)]

//! Provides functionality for managing keys and addresses for a user
pub mod alias;
mod derivation_path;
mod keys;
pub mod pre_genesis;
pub mod store;

use std::collections::BTreeMap;
use std::fmt::Display;
use std::str::FromStr;

use alias::Alias;
use bip39::{Language, Mnemonic, MnemonicType, Seed};
use borsh::{BorshDeserialize, BorshSerialize};
use namada_core::address::{Address, ImplicitAddress};
use namada_core::arith::checked;
use namada_core::chain::BlockHeight;
use namada_core::collections::{HashMap, HashSet};
use namada_core::key::*;
use namada_core::masp::{
    DiversifierIndex, ExtendedSpendingKey, ExtendedViewingKey, PaymentAddress,
};
use namada_core::time::DateTimeUtc;
use namada_ibc::trace::is_ibc_denom;
pub use pre_genesis::gen_key_to_store;
use rand::CryptoRng;
use rand_core::RngCore;
pub use store::{AddressVpType, Store};
use thiserror::Error;
use zeroize::Zeroizing;

pub use self::derivation_path::{DerivationPath, DerivationPathError};
pub use self::keys::{
    DatedKeypair, DatedSpendingKey, DatedViewingKey, DecryptionError,
    StoreSpendingKey, StoredKeypair,
};
pub use self::store::{ConfirmationResponse, ValidatorData, ValidatorKeys};
use crate::store::{derive_hd_secret_key, derive_hd_spending_key};

const DISPOSABLE_KEY_LIFETIME_IN_SECONDS: i64 = 7 * 24 * 60 * 60; // 1 week

/// Captures the interactive parts of the wallet's functioning
pub trait WalletIo: Sized + Clone {
    /// Secure random number generator
    type Rng: RngCore;

    /// Generates a random mnemonic of the given mnemonic type.
    fn generate_mnemonic_code(
        mnemonic_type: MnemonicType,
        rng: &mut Self::Rng,
    ) -> Mnemonic {
        const BITS_PER_BYTE: usize = 8;

        // generate random mnemonic
        let entropy_size = mnemonic_type.entropy_bits() / BITS_PER_BYTE;
        let mut bytes = vec![0u8; entropy_size];
        rand::RngCore::fill_bytes(rng, &mut bytes);
        Mnemonic::from_entropy(&bytes, Language::English)
            .expect("Mnemonic creation should not fail")
    }

    /// Read the password for decryption from the file/env/stdin.
    fn read_password(
        _confirm: bool,
        _target_key: Option<&str>,
    ) -> Zeroizing<String> {
        panic!("attempted to prompt for password in non-interactive mode");
    }

    /// Read an alias from the file/env/stdin.
    fn read_alias(_prompt_msg: &str) -> String {
        panic!("attempted to prompt for alias in non-interactive mode");
    }

    /// Read mnemonic code from the file/env/stdin.
    fn read_mnemonic_code() -> Option<Mnemonic> {
        panic!("attempted to prompt for alias in non-interactive mode");
    }

    /// Read a mnemonic code from the file/env/stdin.
    fn read_mnemonic_passphrase(_confirm: bool) -> Zeroizing<String> {
        panic!("attempted to prompt for alias in non-interactive mode");
    }

    /// The given alias has been selected but conflicts with another alias in
    /// the store. Offer the user to either replace existing mapping, alter the
    /// chosen alias to a name of their choice, or cancel the aliasing.
    fn show_overwrite_confirmation(
        _alias: &Alias,
        _alias_for: &str,
    ) -> store::ConfirmationResponse {
        // Automatically replace aliases in non-interactive mode
        store::ConfirmationResponse::Replace
    }
}

/// Errors of wallet loading and storing
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum LoadStoreError {
    /// Wallet store file not found
    #[error("No wallet store file found at \"{path}\"")]
    NotFound { path: String },
    /// Wallet store decoding error
    #[error("Failed decoding the wallet store: {0}")]
    Decode(toml::de::Error),
    /// Wallet store reading error
    #[error("Failed to read the wallet store from {0}: {1}")]
    ReadWallet(String, String),
    /// Wallet store writing error
    #[error("Failed to write the wallet store: {0}")]
    StoreNewWallet(String),
}

/// Captures the permanent storage parts of the wallet's functioning
pub trait WalletStorage: Sized + Clone {
    /// Save the wallet store to a file.
    fn save<U>(&self, wallet: &Wallet<U>) -> Result<(), LoadStoreError>;

    /// Load a wallet from the store file.
    fn load<U>(&self, wallet: &mut Wallet<U>) -> Result<(), LoadStoreError>;
}

#[cfg(feature = "std")]
/// Implementation of wallet functionality depending on a standard filesystem
pub mod fs {
    use std::fs;
    use std::io::{Read, Write};
    use std::path::PathBuf;

    use fd_lock::RwLock;
    use rand_core::OsRng;

    use super::*;

    /// A trait for deriving WalletStorage for standard filesystems
    pub trait FsWalletStorage: Clone {
        /// The directory in which the wallet is supposed to be stored
        fn store_dir(&self) -> &PathBuf;
    }

    /// Wallet file name
    const FILE_NAME: &str = "wallet.toml";

    impl<F: FsWalletStorage> WalletStorage for F {
        fn save<U>(&self, wallet: &Wallet<U>) -> Result<(), LoadStoreError> {
            let data = wallet.store.encode();
            let wallet_path = self.store_dir().join(FILE_NAME);
            // Make sure the dir exists
            let wallet_dir = wallet_path.parent().unwrap();
            fs::create_dir_all(wallet_dir).map_err(|err| {
                LoadStoreError::StoreNewWallet(err.to_string())
            })?;
            // Write the file
            let mut options = fs::OpenOptions::new();
            options.create(true).write(true).truncate(true);
            let mut lock =
                RwLock::new(options.open(wallet_path).map_err(|err| {
                    LoadStoreError::StoreNewWallet(err.to_string())
                })?);
            let mut guard = lock.write().map_err(|err| {
                LoadStoreError::StoreNewWallet(err.to_string())
            })?;
            guard
                .write_all(data.as_bytes())
                .map_err(|err| LoadStoreError::StoreNewWallet(err.to_string()))
        }

        fn load<U>(
            &self,
            wallet: &mut Wallet<U>,
        ) -> Result<(), LoadStoreError> {
            let wallet_file = self.store_dir().join(FILE_NAME);
            if !wallet_file.exists() {
                return Err(LoadStoreError::NotFound {
                    path: wallet_file.to_string_lossy().to_string(),
                });
            }

            let mut options = fs::OpenOptions::new();
            options.read(true).write(false);
            let lock =
                RwLock::new(options.open(&wallet_file).map_err(|err| {
                    LoadStoreError::ReadWallet(
                        wallet_file.to_string_lossy().into_owned(),
                        err.to_string(),
                    )
                })?);
            let guard = lock.read().map_err(|err| {
                LoadStoreError::ReadWallet(
                    wallet_file.to_string_lossy().into_owned(),
                    err.to_string(),
                )
            })?;
            let mut store = String::new();
            (&*guard).read_to_string(&mut store).map_err(|err| {
                LoadStoreError::ReadWallet(
                    self.store_dir().to_str().unwrap().parse().unwrap(),
                    err.to_string(),
                )
            })?;
            wallet.store =
                Store::decode(&store).map_err(LoadStoreError::Decode)?;
            Ok(())
        }
    }

    /// For a non-interactive filesystem based wallet
    #[derive(Debug, BorshSerialize, BorshDeserialize, Clone)]
    pub struct FsWalletUtils {
        #[borsh(skip)]
        store_dir: PathBuf,
    }

    impl FsWalletUtils {
        /// Initialize a wallet at the given directory
        pub fn new(store_dir: PathBuf) -> Wallet<Self> {
            Wallet::new(Self { store_dir }, Store::default())
        }
    }

    impl WalletIo for FsWalletUtils {
        type Rng = OsRng;
    }

    impl FsWalletStorage for FsWalletUtils {
        fn store_dir(&self) -> &PathBuf {
            &self.store_dir
        }
    }
}

/// Generate a new secret key.
pub fn gen_secret_key(
    scheme: SchemeType,
    csprng: &mut (impl CryptoRng + RngCore),
) -> common::SecretKey {
    match scheme {
        SchemeType::Ed25519 => ed25519::SigScheme::generate(csprng).try_to_sk(),
        SchemeType::Secp256k1 => {
            secp256k1::SigScheme::generate(csprng).try_to_sk()
        }
        SchemeType::Common => common::SigScheme::generate(csprng).try_to_sk(),
    }
    .unwrap()
}

fn gen_spending_key(
    csprng: &mut (impl CryptoRng + RngCore),
) -> ExtendedSpendingKey {
    let mut spend_key = [0; 32];
    csprng.fill_bytes(&mut spend_key);
    masp_primitives::zip32::ExtendedSpendingKey::master(spend_key.as_ref())
        .into()
}

/// The error that is produced when a given key cannot be obtained
#[derive(Error, Debug)]
pub enum FindKeyError {
    /// Could not find a given key in the wallet
    #[error("No key matching {0} found")]
    KeyNotFound(String),
    /// Could not decrypt a given key in the wallet
    #[error("{0}")]
    KeyDecryptionError(keys::DecryptionError),
}

/// Represents a collection of keys and addresses while caching key decryptions
#[derive(Debug)]
pub struct Wallet<U> {
    /// Location where this shielded context is saved
    utils: U,
    store: Store,
    decrypted_key_cache: HashMap<Alias, common::SecretKey>,
    decrypted_spendkey_cache: HashMap<Alias, ExtendedSpendingKey>,
}

impl<U> From<Wallet<U>> for Store {
    fn from(wallet: Wallet<U>) -> Self {
        wallet.store
    }
}

impl<U> Wallet<U> {
    /// Create a new wallet from the given backing store and storage location
    pub fn new(utils: U, store: Store) -> Self {
        Self {
            utils,
            store,
            decrypted_key_cache: HashMap::default(),
            decrypted_spendkey_cache: HashMap::default(),
        }
    }

    /// Add validator data to the store
    pub fn add_validator_data(
        &mut self,
        address: Address,
        keys: ValidatorKeys,
    ) {
        self.store.add_validator_data(address, keys);
    }

    /// Returns a reference to the validator data, if it exists.
    pub fn get_validator_data(&self) -> Option<&ValidatorData> {
        self.store.get_validator_data()
    }

    /// Returns a mut reference to the validator data, if it exists.
    pub fn get_validator_data_mut(&mut self) -> Option<&mut ValidatorData> {
        self.store.get_validator_data_mut()
    }

    /// Take the validator data, if it exists.
    pub fn take_validator_data(&mut self) -> Option<ValidatorData> {
        self.store.take_validator_data()
    }

    /// Returns the validator data, if it exists.
    pub fn into_validator_data(self) -> Option<ValidatorData> {
        self.store.into_validator_data()
    }

    /// Provide immutable access to the backing store
    pub fn store(&self) -> &Store {
        &self.store
    }

    /// Provide mutable access to the backing store
    pub fn store_mut(&mut self) -> &mut Store {
        &mut self.store
    }

    /// Extend this wallet from pre-genesis validator wallet.
    pub fn extend_from_pre_genesis_validator(
        &mut self,
        validator_address: Address,
        validator_alias: Alias,
        other: pre_genesis::ValidatorWallet,
    ) {
        self.store.extend_from_pre_genesis_validator(
            validator_address,
            validator_alias,
            other,
        )
    }

    /// Gets all addresses given a vp_type
    pub fn get_addresses_with_vp_type(
        &self,
        vp_type: AddressVpType,
    ) -> HashSet<Address> {
        self.store.get_addresses_with_vp_type(vp_type)
    }

    /// Add a vp_type to a given address
    pub fn add_vp_type_to_address(
        &mut self,
        vp_type: AddressVpType,
        address: Address,
    ) {
        // defaults to an empty set
        self.store.add_vp_type_to_address(vp_type, address)
    }

    /// Get addresses with tokens VP type keyed and ordered by their aliases.
    pub fn tokens_with_aliases(&self) -> BTreeMap<String, Address> {
        self.get_addresses_with_vp_type(AddressVpType::Token)
            .into_iter()
            .map(|addr| {
                let alias = self.lookup_alias(&addr);
                (alias, addr)
            })
            .collect()
    }

    /// Find the stored address by an alias.
    pub fn find_address(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<std::borrow::Cow<'_, Address>> {
        Alias::is_reserved(alias.as_ref())
            .map(std::borrow::Cow::Owned)
            .or_else(|| {
                self.store
                    .find_address(alias)
                    .map(std::borrow::Cow::Borrowed)
            })
    }

    /// Find an alias by the address if it's in the wallet.
    pub fn find_alias(&self, address: &Address) -> Option<&Alias> {
        self.store.find_alias(address)
    }

    /// Try to find an alias for a given address from the wallet. If not found,
    /// formats the address into a string.
    pub fn lookup_alias(&self, addr: &Address) -> String {
        match self.find_alias(addr) {
            Some(alias) => format!("{}", alias),
            None => format!("{}", addr),
        }
    }

    /// Try to find an alias of the base token in the given IBC denomination
    /// from the wallet. If not found, formats the IBC denomination into a
    /// string.
    pub fn lookup_ibc_token_alias(&self, ibc_denom: impl AsRef<str>) -> String {
        // Convert only an IBC denom or a Namada address since an NFT trace
        // doesn't have the alias
        is_ibc_denom(&ibc_denom)
            .map(|(trace_path, base_token)| {
                let base_token_alias = match Address::decode(&base_token) {
                    Ok(base_token) => self.lookup_alias(&base_token),
                    Err(_) => base_token,
                };
                if trace_path.is_empty() {
                    base_token_alias
                } else {
                    format!("{}/{}", trace_path, base_token_alias)
                }
            })
            .or_else(|| {
                // It's not an IBC denom, but could be a raw Namada address
                match Address::decode(&ibc_denom) {
                    Ok(addr) => Some(self.lookup_alias(&addr)),
                    Err(_) => None,
                }
            })
            .unwrap_or(ibc_denom.as_ref().to_string())
    }

    /// Find the viewing key with the given alias in the wallet and return it
    pub fn find_viewing_key(
        &self,
        alias: impl AsRef<str>,
    ) -> Result<&ExtendedViewingKey, FindKeyError> {
        self.store.find_viewing_key(alias.as_ref()).ok_or_else(|| {
            FindKeyError::KeyNotFound(alias.as_ref().to_string())
        })
    }

    /// Find the birthday of the given alias
    pub fn find_birthday(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<&BlockHeight> {
        self.store.find_birthday(alias.as_ref())
    }

    /// Find the diversifier index of the given alias
    pub fn find_diversifier_index(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<&DiversifierIndex> {
        self.store.find_diversifier_index(alias.as_ref())
    }

    /// Find the payment address with the given alias in the wallet and return
    /// it
    pub fn find_payment_addr(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<&PaymentAddress> {
        self.store.find_payment_addr(alias.as_ref())
    }

    /// Find an alias by the payment address if it's in the wallet.
    pub fn find_alias_by_payment_addr(
        &self,
        payment_address: &PaymentAddress,
    ) -> Option<&Alias> {
        self.store.find_alias_by_payment_addr(payment_address)
    }

    /// Get all known keys by their alias, paired with PKH, if known.
    pub fn get_secret_keys(
        &self,
    ) -> HashMap<
        String,
        (&StoredKeypair<common::SecretKey>, Option<&PublicKeyHash>),
    > {
        self.store
            .get_secret_keys()
            .into_iter()
            .map(|(alias, value)| (alias.into(), value))
            .collect()
    }

    /// Get all known public keys by their alias.
    pub fn get_public_keys(&self) -> HashMap<String, common::PublicKey> {
        self.store
            .get_public_keys()
            .iter()
            .map(|(alias, value)| (alias.into(), value.clone()))
            .collect()
    }

    /// Get all known addresses by their alias, paired with PKH, if known.
    pub fn get_addresses(&self) -> HashMap<String, Address> {
        self.store
            .get_addresses()
            .iter()
            .map(|(alias, value)| (alias.into(), value.clone()))
            .collect()
    }

    /// Get all known payment addresses by their alias
    pub fn get_payment_addrs(&self) -> HashMap<String, PaymentAddress> {
        self.store
            .get_payment_addrs()
            .iter()
            .map(|(alias, value)| (alias.into(), *value))
            .collect()
    }

    /// Get all known viewing keys by their alias
    pub fn get_viewing_keys(&self) -> HashMap<String, ExtendedViewingKey> {
        self.store
            .get_viewing_keys()
            .iter()
            .map(|(alias, value)| (alias.into(), *value))
            .collect()
    }

    /// Get all known viewing keys by their alias
    pub fn get_spending_keys(
        &self,
    ) -> HashMap<String, &StoredKeypair<StoreSpendingKey>> {
        self.store
            .get_spending_keys()
            .iter()
            .map(|(alias, value)| (alias.into(), value))
            .collect()
    }

    /// Check if alias is an encrypted secret key
    pub fn is_encrypted_secret_key(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<bool> {
        self.store
            .find_secret_key(alias)
            .map(|stored_keypair| stored_keypair.is_encrypted())
    }

    /// Check if alias is an encrypted spending key
    pub fn is_encrypted_spending_key(
        &self,
        alias: impl AsRef<str>,
    ) -> Option<bool> {
        self.store
            .find_spending_key(alias)
            .map(|stored_spend_key| stored_spend_key.is_encrypted())
    }
}

impl<U: WalletStorage> Wallet<U> {
    /// Load a wallet from the store file.
    pub fn load(&mut self) -> Result<(), LoadStoreError> {
        self.utils.clone().load(self)
    }

    /// Save the wallet store to a file.
    pub fn save(&self) -> Result<(), LoadStoreError> {
        self.utils.save(self)
    }
}

impl<U: WalletIo> Wallet<U> {
    /// Restore a spending key from the user mnemonic code (read from stdin)
    /// using a given ZIP32 derivation path and insert it into the store with
    /// the provided alias, converted to lower case.
    /// The key is encrypted with the provided password. If no password
    /// provided, will prompt for password from stdin.
    /// Stores the key in decrypted key cache and returns the alias of the key
    /// and a reference-counting pointer to the key.
    #[allow(clippy::too_many_arguments)]
    pub fn derive_store_spending_key_from_mnemonic_code(
        &mut self,
        alias: String,
        alias_force: bool,
        birthday: Option<BlockHeight>,
        unsafe_pure_zip32: bool,
        derivation_path: DerivationPath,
        mnemonic_passphrase: Option<(Mnemonic, Zeroizing<String>)>,
        prompt_bip39_passphrase: bool,
        password: Option<Zeroizing<String>>,
    ) -> Option<(String, ExtendedSpendingKey)> {
        let (mnemonic, passphrase) =
            if let Some(mnemonic_passphrase) = mnemonic_passphrase {
                mnemonic_passphrase
            } else {
                let mnemonic = U::read_mnemonic_code()?;
                let passphrase = if prompt_bip39_passphrase {
                    U::read_mnemonic_passphrase(false)
                } else {
                    Zeroizing::default()
                };
                (mnemonic, passphrase)
            };
        let seed = Seed::new(&mnemonic, &passphrase);
        let seed = if unsafe_pure_zip32 {
            seed.as_bytes()
        } else {
            // Path to obtain the ZIP32 seed
            let (zip32_seed_path, scheme) = DerivationPath::modified_zip32();
            // Obtain the ZIP32 seed using SLIP10
            &derive_hd_secret_key(scheme, seed.as_bytes(), zip32_seed_path)
                .try_to_sk::<ed25519::SecretKey>()
                .expect("Expected Ed25519 key")
                .0
                .to_bytes()[..]
        };
        // Now ZIP32 derive the extended spending key from the new seed
        let spend_key = derive_hd_spending_key(seed, derivation_path.clone());

        self.insert_spending_key(
            alias,
            alias_force,
            spend_key,
            birthday,
            password,
            Some(derivation_path),
        )
        .map(|alias| (alias, spend_key))
    }

    /// Find a derivation path by viewing key
    pub fn find_path_by_viewing_key(
        &self,
        vk: &ExtendedViewingKey,
    ) -> Result<DerivationPath, FindKeyError> {
        self.store
            .find_path_by_viewing_key(vk)
            .ok_or_else(|| FindKeyError::KeyNotFound(vk.to_string()))
    }

    /// Restore a keypair from the user mnemonic code (read from stdin) using
    /// a given BIP44 derivation path and derive an implicit address from its
    /// public part and insert them into the store with the provided alias,
    /// converted to lower case. If none provided, the alias will be the public
    /// key hash (in lowercase too).
    /// The key is encrypted with the provided password. If no password
    /// provided, will prompt for password from stdin.
    /// Stores the key in decrypted key cache and returns the alias of the key
    /// and a reference-counting pointer to the key.
    ///
    /// Any usage of this function should be careful not expose a shielded key
    /// that may be derived via modified ZIP32 from this key (specifically when
    /// the derivation path and schema matching `DerivationPath::modified_zip32`
    /// and no encryption password is being used).
    #[allow(clippy::too_many_arguments)]
    pub fn derive_store_key_from_mnemonic_code(
        &mut self,
        scheme: SchemeType,
        alias: Option<String>,
        alias_force: bool,
        derivation_path: DerivationPath,
        mnemonic_passphrase: Option<(Mnemonic, Zeroizing<String>)>,
        prompt_bip39_passphrase: bool,
        password: Option<Zeroizing<String>>,
    ) -> Option<(String, common::SecretKey)> {
        let (mnemonic, passphrase) =
            if let Some(mnemonic_passphrase) = mnemonic_passphrase {
                mnemonic_passphrase
            } else {
                let mnemonic = U::read_mnemonic_code()?;
                let passphrase = if prompt_bip39_passphrase {
                    U::read_mnemonic_passphrase(false)
                } else {
                    Zeroizing::default()
                };
                (mnemonic, passphrase)
            };
        let seed = Seed::new(&mnemonic, &passphrase);
        let sk = derive_hd_secret_key(
            scheme,
            seed.as_bytes(),
            derivation_path.clone(),
        );

        self.insert_keypair(
            alias.unwrap_or_default(),
            alias_force,
            sk.clone(),
            password,
            None,
            Some(derivation_path),
        )
        .map(|alias| (alias, sk))
    }

    /// Generate a spending key similarly to how it's done for keypairs
    pub fn gen_store_spending_key(
        &mut self,
        alias: String,
        birthday: Option<BlockHeight>,
        password: Option<Zeroizing<String>>,
        force_alias: bool,
        csprng: &mut (impl CryptoRng + RngCore),
    ) -> Option<(String, ExtendedSpendingKey)> {
        let spend_key = gen_spending_key(csprng);
        self.insert_spending_key(
            alias,
            force_alias,
            spend_key,
            birthday,
            password,
            None,
        )
        .map(|alias| (alias, spend_key))
    }

    /// Generate a new keypair, derive an implicit address from its public key
    /// and insert them into the store with the provided alias, converted to
    /// lower case. If none provided, the alias will be the public key hash (in
    /// lowercase too). If the alias already exists, optionally force overwrite
    /// the keypair for the alias.
    /// If no encryption password is provided, the keypair will be stored raw
    /// without encryption.
    /// Stores the key in decrypted key cache and returns the alias of the key
    /// and a reference-counting pointer to the key.
    pub fn gen_store_secret_key(
        &mut self,
        scheme: SchemeType,
        alias: Option<String>,
        alias_force: bool,
        password: Option<Zeroizing<String>>,
        rng: &mut (impl CryptoRng + RngCore),
    ) -> Option<(String, common::SecretKey)> {
        let sk = gen_secret_key(scheme, rng);
        self.insert_keypair(
            alias.unwrap_or_default(),
            alias_force,
            sk.clone(),
            password,
            None,
            None,
        )
        .map(|alias| (alias, sk))
    }

    /// Generate a BIP39 mnemonic code, and derive HD wallet seed from it using
    /// the given passphrase. If no passphrase is provided, optionally prompt
    /// for a passphrase.
    pub fn gen_hd_seed(
        passphrase: Option<Zeroizing<String>>,
        rng: &mut U::Rng,
        prompt_bip39_passphrase: bool,
    ) -> (Mnemonic, Seed) {
        const MNEMONIC_TYPE: MnemonicType = MnemonicType::Words24;
        let mnemonic = U::generate_mnemonic_code(MNEMONIC_TYPE, rng);
        println!(
            "Safely store your {} words mnemonic.",
            MNEMONIC_TYPE.word_count()
        );
        println!("{}", mnemonic.clone().into_phrase());

        let passphrase = passphrase.unwrap_or_else(|| {
            if prompt_bip39_passphrase {
                U::read_mnemonic_passphrase(true)
            } else {
                Zeroizing::default()
            }
        });
        let seed = Seed::new(&mnemonic, &passphrase);
        (mnemonic, seed)
    }

    /// Derive a keypair from the given seed and path, derive an implicit
    /// address from this keypair, and insert them into the store with the
    /// provided alias, converted to lower case. If none provided, the alias
    /// will be the public key hash (in lowercase too). If the alias already
    /// exists, optionally force overwrite the keypair for the alias.
    /// If no encryption password is provided, the keypair will be stored raw
    /// without encryption.
    /// Stores the key in decrypted key cache and returns the alias of the key
    /// and the key itself.
    ///
    /// Any usage of this function should be careful not expose a shielded key
    /// that may be derived via modified ZIP32 from this key (specifically when
    /// the derivation path and schema matching `DerivationPath::modified_zip32`
    /// and no encryption password is being used).
    pub fn derive_store_hd_secret_key(
        &mut self,
        scheme: SchemeType,
        alias: Option<String>,
        alias_force: bool,
        seed: Seed,
        derivation_path: DerivationPath,
        password: Option<Zeroizing<String>>,
    ) -> Option<(String, common::SecretKey)> {
        let sk = derive_hd_secret_key(
            scheme,
            seed.as_bytes(),
            derivation_path.clone(),
        );
        self.insert_keypair(
            alias.unwrap_or_default(),
            alias_force,
            sk.clone(),
            password,
            None,
            Some(derivation_path),
        )
        .map(|alias| (alias, sk))
    }

    /// Derive a masp shielded key from the given seed and path, and insert it
    /// into the store with the provided alias, converted to lower case. If the
    /// alias already exists, optionally force overwrite the key for the
    /// alias.
    ///
    /// An optional birthday can be provided saying that this key was created
    /// after this blockheight.
    ///
    /// If no encryption password is provided, the key will be stored raw
    /// without encryption.
    ///
    /// Stores the key in decrypted key cache and returns the alias of the key
    /// and the key itself.
    pub fn derive_store_hd_spending_key(
        &mut self,
        alias: String,
        force_alias: bool,
        birthday: Option<BlockHeight>,
        seed: Seed,
        derivation_path: DerivationPath,
        password: Option<Zeroizing<String>>,
    ) -> Option<(String, ExtendedSpendingKey)> {
        let spend_key =
            derive_hd_spending_key(seed.as_bytes(), derivation_path.clone());
        self.insert_spending_key(
            alias,
            force_alias,
            spend_key,
            birthday,
            password,
            Some(derivation_path),
        )
        .map(|alias| (alias, spend_key))
    }

    /// Generate a disposable signing key for fee payment and store it under the
    /// precomputed alias in the wallet. This is simply a wrapper around
    /// `gen_key` to manage the alias
    pub fn gen_disposable_signing_key(
        &mut self,
        rng: &mut (impl CryptoRng + RngCore),
    ) -> common::SecretKey {
        #[allow(clippy::disallowed_methods)]
        let current_unix_timestamp = DateTimeUtc::now().to_unix_timestamp();

        let disposable_keys_to_gc = self
            .store
            .get_public_keys()
            .keys()
            .filter(|key_alias| {
                check_if_disposable_key_and(
                    key_alias,
                    |_pkh, key_creation_unix_timestamp| {
                        let seconds_since_key_creation = checked!(
                            current_unix_timestamp
                                - key_creation_unix_timestamp
                        )
                        .expect(
                            "Key should have been created before the current \
                             time instant!",
                        );
                        seconds_since_key_creation
                            > DISPOSABLE_KEY_LIFETIME_IN_SECONDS
                    },
                )
            })
            .cloned()
            .collect::<Vec<_>>();

        for key_alias in disposable_keys_to_gc {
            self.store.remove_alias(&key_alias);
        }

        let sk = gen_secret_key(SchemeType::Ed25519, rng);
        let key_alias = {
            let pkh: PublicKeyHash = (&sk.to_public()).into();
            disposable_key_alias(&pkh, current_unix_timestamp)
        };

        println!("Created disposable keypair with alias {key_alias}");

        // TODO(namada#3239): once the wrapper transaction has been applied,
        // this key can be deleted from wallet (the transaction being
        // accepted is not enough cause we could end up doing a
        // rollback)
        self.insert_keypair(key_alias, false, sk.clone(), None, None, None)
            .expect("Failed to store disposable signing key");

        sk
    }

    /// Find the stored key by an alias, a public key hash or a public key.
    /// If the key is encrypted and password not supplied, then password will be
    /// interactively prompted. Any keys that are decrypted are stored in and
    /// read from a cache to avoid prompting for password multiple times.
    pub fn find_secret_key(
        &mut self,
        alias_pkh_or_pk: impl AsRef<str>,
        password: Option<Zeroizing<String>>,
    ) -> Result<common::SecretKey, FindKeyError> {
        // Try cache first
        if let Some(cached_key) = self
            .decrypted_key_cache
            .get(&Alias::from(alias_pkh_or_pk.as_ref()))
        {
            return Ok(cached_key.clone());
        }
        // If not cached, look-up in store
        let stored_key = self
            .store
            .find_secret_key(alias_pkh_or_pk.as_ref())
            .ok_or_else(|| {
            FindKeyError::KeyNotFound(alias_pkh_or_pk.as_ref().to_string())
        })?;
        Self::decrypt_stored_key::<_, _>(
            &mut self.decrypted_key_cache,
            stored_key,
            alias_pkh_or_pk.into(),
            password,
        )
    }

    /// Find a public key in the wallet from the given implicit address.
    pub fn find_public_key_from_implicit_addr(
        &self,
        implicit_addr: &ImplicitAddress,
    ) -> Result<common::PublicKey, FindKeyError> {
        self.store
            .get_public_keys()
            .iter()
            .find_map(|(_, pubkey)| {
                (ImplicitAddress::from(pubkey) == *implicit_addr)
                    .then(|| pubkey.clone())
            })
            .ok_or_else(|| {
                FindKeyError::KeyNotFound(
                    Address::Implicit(implicit_addr.clone()).to_string(),
                )
            })
    }

    /// Find the public key by an alias or a public key hash.
    pub fn find_public_key(
        &self,
        alias_or_pkh: impl AsRef<str>,
    ) -> Result<common::PublicKey, FindKeyError> {
        self.store
            .find_public_key(alias_or_pkh.as_ref())
            .cloned()
            .ok_or_else(|| {
                FindKeyError::KeyNotFound(alias_or_pkh.as_ref().to_string())
            })
    }

    /// Find the spending key with the given alias in the wallet and return it.
    /// If the spending key is encrypted but a password is not supplied, then it
    /// will be interactively prompted.
    pub fn find_spending_key(
        &mut self,
        alias: impl AsRef<str>,
        password: Option<Zeroizing<String>>,
    ) -> Result<ExtendedSpendingKey, FindKeyError> {
        // Try cache first
        if let Some(cached_key) = self
            .decrypted_spendkey_cache
            .get(&Alias::from(alias.as_ref()))
        {
            return Ok(*cached_key);
        }
        // If not cached, look-up in store
        let stored_spendkey = self
            .store
            .find_spending_key(alias.as_ref())
            .ok_or_else(|| {
                FindKeyError::KeyNotFound(alias.as_ref().to_string())
            })?;
        Self::decrypt_stored_key::<_, _>(
            &mut self.decrypted_spendkey_cache,
            stored_spendkey,
            alias.into(),
            password,
        )
    }

    /// Find the stored key by a public key.
    /// If the key is encrypted and password not supplied, then password will be
    /// interactively prompted for. Any keys that are decrypted are stored in
    /// and read from a cache to avoid prompting for password multiple times.
    pub fn find_key_by_pk(
        &mut self,
        pk: &common::PublicKey,
        password: Option<Zeroizing<String>>,
    ) -> Result<common::SecretKey, FindKeyError> {
        // Try to look-up alias for the given pk. Otherwise, use the PKH string.
        let pkh: PublicKeyHash = pk.into();
        self.find_key_by_pkh(&pkh, password)
    }

    /// Find a derivation path by public key hash
    pub fn find_path_by_pkh(
        &self,
        pkh: &PublicKeyHash,
    ) -> Result<DerivationPath, FindKeyError> {
        self.store
            .find_path_by_pkh(pkh)
            .ok_or_else(|| FindKeyError::KeyNotFound(pkh.to_string()))
    }

    /// Find the public key by a public key hash.
    /// If the key is encrypted and password not supplied, then password will be
    /// interactively prompted for. Any keys that are decrypted are stored in
    /// and read from a cache to avoid prompting for password multiple times.
    pub fn find_public_key_by_pkh(
        &self,
        pkh: &PublicKeyHash,
    ) -> Result<common::PublicKey, FindKeyError> {
        self.store
            .find_public_key_by_pkh(pkh)
            .cloned()
            .ok_or_else(|| FindKeyError::KeyNotFound(pkh.to_string()))
    }

    /// Find the stored key by a public key hash.
    /// If the key is encrypted and password is not supplied, then password will
    /// be interactively prompted for. Any keys that are decrypted are stored in
    /// and read from a cache to avoid prompting for password multiple times.
    pub fn find_key_by_pkh(
        &mut self,
        pkh: &PublicKeyHash,
        password: Option<Zeroizing<String>>,
    ) -> Result<common::SecretKey, FindKeyError> {
        // Try to look-up alias for the given pk. Otherwise, use the PKH string.
        let alias = self
            .store
            .find_alias_by_pkh(pkh)
            .unwrap_or_else(|| pkh.to_string().into());
        // Try read cache
        if let Some(cached_key) = self.decrypted_key_cache.get(&alias) {
            return Ok(cached_key.clone());
        }
        // Look-up from store
        let stored_key = self
            .store
            .find_key_by_pkh(pkh)
            .ok_or_else(|| FindKeyError::KeyNotFound(pkh.to_string()))?;
        Self::decrypt_stored_key(
            &mut self.decrypted_key_cache,
            stored_key,
            alias,
            password,
        )
    }

    /// Decrypt stored key, if it's not stored un-encrypted.
    /// If a given storage key needs to be decrypted and password is not
    /// supplied, then interactively prompt for password and if successfully
    /// decrypted, store it in a cache.
    fn decrypt_stored_key<
        V: Clone,
        T: FromStr + Display + BorshSerialize + BorshDeserialize + Clone + Into<V>,
    >(
        decrypted_key_cache: &mut HashMap<Alias, V>,
        stored_key: &StoredKeypair<T>,
        alias: Alias,
        password: Option<Zeroizing<String>>,
    ) -> Result<V, FindKeyError>
    where
        <T as std::str::FromStr>::Err: Display,
    {
        match stored_key {
            StoredKeypair::Encrypted(encrypted) => {
                let key = match password {
                    Some(pwd) => encrypted.decrypt(pwd),
                    None => {
                        // Two attempts to get the password right in interactive
                        // mode
                        let mut key_result =
                            Err(keys::DecryptionError::EmptyPassword);
                        for _ in 0..2 {
                            let pwd = U::read_password(
                                false,
                                Some(&alias.to_string()),
                            );
                            key_result = encrypted.decrypt(pwd);
                            if key_result.is_ok() {
                                break;
                            }
                        }

                        key_result
                    }
                }
                .map_err(FindKeyError::KeyDecryptionError)?;

                decrypted_key_cache.insert(alias.clone(), key.into());
                decrypted_key_cache
                    .get(&alias)
                    .cloned()
                    .ok_or_else(|| FindKeyError::KeyNotFound(alias.to_string()))
            }
            StoredKeypair::Raw(raw) => Ok(raw.clone().into()),
        }
    }

    /// Add a new address with the given alias. If the alias is already used,
    /// will ask whether the existing alias should be replaced, a different
    /// alias is desired, or the alias creation should be cancelled. Return
    /// the chosen alias if the address has been added, otherwise return
    /// nothing.
    pub fn insert_address(
        &mut self,
        alias: impl AsRef<str>,
        address: Address,
        force_alias: bool,
    ) -> Option<String> {
        self.store
            .insert_address::<U>(alias.into(), address, force_alias)
            .map(Into::into)
    }

    /// Add a new keypair with the given alias. If the alias is already used,
    /// will ask whether the existing alias should be replaced, a different
    /// alias is desired, or the alias creation should be cancelled. Return
    /// the chosen alias if the keypair has been added, otherwise return
    /// nothing.
    pub fn insert_keypair(
        &mut self,
        alias: String,
        alias_force: bool,
        sk: common::SecretKey,
        password: Option<Zeroizing<String>>,
        address: Option<Address>,
        path: Option<DerivationPath>,
    ) -> Option<String> {
        self.store
            .insert_keypair::<U>(
                alias.into(),
                sk.clone(),
                password,
                address,
                path,
                alias_force,
            )
            .map(|alias| {
                // Cache the newly added key
                self.decrypted_key_cache.insert(alias.clone(), sk);
                alias.into()
            })
    }

    /// Insert a new public key with the given alias. If the alias is already
    /// used, then display a prompt for overwrite confirmation.
    pub fn insert_public_key(
        &mut self,
        alias: String,
        pubkey: common::PublicKey,
        address: Option<Address>,
        path: Option<DerivationPath>,
        force_alias: bool,
    ) -> Option<String> {
        self.store
            .insert_public_key::<U>(
                alias.into(),
                pubkey,
                address,
                path,
                force_alias,
            )
            .map(Into::into)
    }

    /// Insert a viewing key into the wallet under the given alias
    pub fn insert_viewing_key(
        &mut self,
        alias: String,
        view_key: ExtendedViewingKey,
        birthday: Option<BlockHeight>,
        force_alias: bool,
        path: Option<DerivationPath>,
    ) -> Option<String> {
        self.store
            .insert_viewing_key::<U>(
                alias.into(),
                view_key,
                birthday,
                path,
                force_alias,
            )
            .map(Into::into)
    }

    /// Insert a spending key into the wallet under the given alias
    pub fn insert_spending_key(
        &mut self,
        alias: String,
        force_alias: bool,
        spend_key: ExtendedSpendingKey,
        birthday: Option<BlockHeight>,
        password: Option<Zeroizing<String>>,
        path: Option<DerivationPath>,
    ) -> Option<String> {
        self.store
            .insert_spending_key::<U>(
                alias.into(),
                spend_key,
                birthday,
                password,
                path,
                force_alias,
            )
            .inspect(|alias| {
                // Cache the newly added key
                self.decrypted_spendkey_cache
                    .insert(alias.clone(), spend_key);
            })
            .map(Into::into)
    }

    /// Insert a payment address into the wallet under the given alias
    pub fn insert_payment_addr(
        &mut self,
        alias: String,
        payment_addr: PaymentAddress,
        force_alias: bool,
    ) -> Option<String> {
        self.store
            .insert_payment_addr::<U>(alias.into(), payment_addr, force_alias)
            .map(Into::into)
    }

    /// Insert a diversifier index into the wallet under the given alias. Useful
    /// for sequential payment address generation.
    pub fn insert_diversifier_index(
        &mut self,
        alias: String,
        div_index: DiversifierIndex,
    ) -> Option<String> {
        self.store
            .insert_diversifier_index(alias.into(), div_index)
            .map(Into::into)
    }

    /// Extend this wallet from another wallet (typically pre-genesis).
    /// Note that this method ignores `store.validator_data` if any.
    pub fn extend(&mut self, wallet: Self) {
        self.store.extend(wallet.store)
    }

    /// Remove keys and addresses associated with the given alias
    pub fn remove_all_by_alias(&mut self, alias: String) {
        self.store.remove_alias(&alias.into())
    }
}

#[inline]
fn disposable_key_alias(pkh: &PublicKeyHash, timestamp: i64) -> String {
    format!("disposable-key-{pkh}-created-at-{timestamp}")
}

#[inline]
fn check_if_disposable_key_and<F: FnOnce(&PublicKeyHash, i64) -> bool>(
    key_alias: &Alias,
    callback: F,
) -> bool {
    let Some((_, rest)) = key_alias.as_ref().split_once("disposable-key-")
    else {
        return false;
    };
    let Some((key_hash_str, timestamp_str)) = rest.split_once("-created-at-")
    else {
        return false;
    };
    let Some(key_hash): Option<PublicKeyHash> =
        key_hash_str.to_uppercase().parse().ok()
    else {
        return false;
    };
    let Some(timestamp): Option<i64> = timestamp_str.parse().ok() else {
        return false;
    };
    callback(&key_hash, timestamp)
}

pub mod test_utils {
    use rand_core::OsRng;

    use crate::{LoadStoreError, Wallet, WalletIo, WalletStorage};

    #[derive(Clone)]
    pub struct TestWalletUtils;

    impl WalletIo for TestWalletUtils {
        type Rng = OsRng;
    }

    impl WalletStorage for TestWalletUtils {
        fn save<U>(&self, _: &Wallet<U>) -> Result<(), LoadStoreError> {
            unimplemented!()
        }

        fn load<U>(&self, _: &mut Wallet<U>) -> Result<(), LoadStoreError> {
            unimplemented!()
        }
    }
}

#[cfg(test)]
mod tests {
    use namada_core::key::testing::{keypair_1, keypair_2, keypair_3};
    use rand_core::OsRng;

    use super::*;
    use crate::test_utils::TestWalletUtils;

    #[test]
    fn test_disposable_key_alias_invalid() {
        assert!(!check_if_disposable_key_and(
            &Alias::from("bertha"),
            |_h, _t| { panic!("Bertha's key is not disposable!") }
        ));
    }

    #[test]
    fn test_disposable_key_alias_parsing() {
        let sk = keypair_1();

        let pkh: PublicKeyHash = (&sk.to_public()).into();
        let timestamp = 12345;
        let alias = Alias::from(disposable_key_alias(&pkh, timestamp));

        assert!(check_if_disposable_key_and(&alias, |h, t| {
            assert_eq!(pkh, *h);
            assert_eq!(timestamp, t);
            true
        }));
    }

    #[test]
    fn test_disposable_keys_are_garbage_collected() {
        let mut wallet = Wallet {
            utils: TestWalletUtils,
            store: Default::default(),
            decrypted_key_cache: Default::default(),
            decrypted_spendkey_cache: Default::default(),
        };

        #[allow(clippy::disallowed_methods)]
        let keys = [
            (keypair_1(), DateTimeUtc::now().to_unix_timestamp()),
            // NB: these keys should be deleted
            (keypair_2(), 0),
            (keypair_3(), 0),
        ];

        for (sk, timestamp) in keys {
            let pkh: PublicKeyHash = (&sk.to_public()).into();
            wallet.insert_keypair(
                disposable_key_alias(&pkh, timestamp),
                true,
                sk,
                None,
                None,
                None,
            );
        }

        // add a new key - length should be 2 now
        let new_key = wallet.gen_disposable_signing_key(&mut OsRng);
        assert_eq!(wallet.store.get_public_keys().len(), 2);

        // check that indeed the first keypair was not gc'd
        let keypair_1_pk = keypair_1().to_public();
        assert!(
            wallet
                .store
                .get_public_keys()
                .values()
                .any(|pk| *pk == keypair_1_pk)
        );

        // check that the only other present key is the newly generated sk
        let new_key_pk = new_key.to_public();
        assert!(
            wallet
                .store
                .get_public_keys()
                .values()
                .any(|pk| *pk == new_key_pk)
        );
    }
}