neo3/neo_wallets/wallet/
backup.rs1use crate::neo_wallets::{Wallet, WalletError};
2use std::{fs::File, io::Write, path::PathBuf};
3
4pub struct WalletBackup;
6
7impl WalletBackup {
8 pub fn backup(wallet: &Wallet, path: PathBuf) -> Result<(), WalletError> {
33 let nep6 = wallet.to_nep6()?;
35
36 let json = serde_json::to_string_pretty(&nep6)
38 .map_err(|e| WalletError::AccountState(format!("Serialization error: {e}")))?;
39
40 let mut file = File::create(path).map_err(|e| WalletError::IoError(e))?;
42
43 file.write_all(json.as_bytes()).map_err(|e| WalletError::IoError(e))?;
44
45 Ok(())
46 }
47
48 pub fn recover(path: PathBuf) -> Result<Wallet, WalletError> {
70 let file_content = std::fs::read_to_string(path).map_err(|e| WalletError::IoError(e))?;
72
73 let nep6_wallet = serde_json::from_str(&file_content)
75 .map_err(|e| WalletError::AccountState(format!("Deserialization error: {e}")))?;
76
77 Wallet::from_nep6(nep6_wallet)
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use std::{fs, path::PathBuf};
85
86 use crate::{
87 neo_protocol::{Account, AccountTrait},
88 neo_wallets::{Wallet, WalletBackup, WalletTrait},
89 };
90
91 #[test]
92 fn test_backup_and_recover() {
93 let mut wallet = Wallet::new();
95 let account = Account::create().expect("Should be able to create account in test");
96 wallet.add_account(account);
97
98 wallet.encrypt_accounts("test_password");
100
101 let temp_file = tempfile::NamedTempFile::new()
103 .expect("Should be able to create temporary file in test");
104 let backup_path = temp_file.path().with_extension("json");
105
106 WalletBackup::backup(&wallet, backup_path.clone())
108 .expect("Should be able to backup wallet in test");
109
110 assert!(backup_path.exists());
112
113 let recovered_wallet = WalletBackup::recover(backup_path.clone())
115 .expect("Should be able to recover wallet in test");
116
117 assert_eq!(wallet.name(), recovered_wallet.name());
119 assert_eq!(wallet.version(), recovered_wallet.version());
120 assert_eq!(wallet.accounts().len(), recovered_wallet.accounts().len());
121
122 fs::remove_file(backup_path).expect("Should be able to remove backup file in test");
124 }
125}