Normalize line endings

This commit is contained in:
Anynomous
2025-09-18 14:51:29 +02:00
parent aed932726c
commit 86de7c6bcd
165 changed files with 0 additions and 53523 deletions
-395
View File
@@ -1,395 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Default wallet lifecycle provider
use crate::config::{
config, GlobalWalletConfig, GlobalWalletConfigMembers, TorConfig, WalletConfig, GRIN_WALLET_DIR,
};
use crate::core::global;
use crate::keychain::Keychain;
use crate::libwallet::{Error, NodeClient, WalletBackend, WalletInitStatus, WalletLCProvider};
use crate::lifecycle::seed::WalletSeed;
use crate::util::secp::key::SecretKey;
use crate::util::ZeroingString;
use crate::LMDBBackend;
use grin_util::logger::LoggingConfig;
use std::fs;
use std::path::PathBuf;
use std::path::MAIN_SEPARATOR;
// Helper fuction to format paths according to OS, avoids bugs on Linux
pub fn fmt_path(path: String) -> String {
let sep = &MAIN_SEPARATOR.to_string();
let path = path.replace("/", &sep);
let path = path.replace("\\", &sep);
path
}
pub struct DefaultLCProvider<'a, C, K>
where
C: NodeClient + 'a,
K: Keychain + 'a,
{
data_dir: String,
node_client: C,
backend: Option<Box<dyn WalletBackend<'a, C, K> + 'a>>,
}
impl<'a, C, K> DefaultLCProvider<'a, C, K>
where
C: NodeClient + 'a,
K: Keychain + 'a,
{
/// Create new provider
pub fn new(node_client: C) -> Self {
DefaultLCProvider {
node_client,
data_dir: "default".to_owned(),
backend: None,
}
}
}
impl<'a, C, K> WalletLCProvider<'a, C, K> for DefaultLCProvider<'a, C, K>
where
C: NodeClient + 'a,
K: Keychain + 'a,
{
fn set_top_level_directory(&mut self, dir: &str) -> Result<(), Error> {
self.data_dir = dir.to_owned();
Ok(())
}
fn get_top_level_directory(&self) -> Result<String, Error> {
let sep = &MAIN_SEPARATOR.to_string();
let data_dir = self
.data_dir
.to_owned()
.replace("/", &sep)
.replace("\\", &sep);
Ok(data_dir)
}
fn create_config(
&self,
chain_type: &global::ChainTypes,
file_name: &str,
wallet_config: Option<WalletConfig>,
logging_config: Option<LoggingConfig>,
tor_config: Option<TorConfig>,
) -> Result<(), Error> {
let mut default_config = GlobalWalletConfig::for_chain(&chain_type);
let config_file_version = match default_config.members.as_ref() {
Some(m) => m.clone().config_file_version,
None => None,
};
let logging = match logging_config {
Some(l) => Some(l),
None => match default_config.members.as_ref() {
Some(m) => m.clone().logging,
None => None,
},
};
// Check if config was provided, if not load default and set update to "true"
let (wallet, update) = match wallet_config {
Some(w) => (w, false),
None => match default_config.members.as_ref() {
Some(m) => (m.clone().wallet, true),
None => (WalletConfig::default(), true),
},
};
let tor = match tor_config {
Some(t) => Some(t),
None => match default_config.members.as_ref() {
Some(m) => m.clone().tor,
None => Some(TorConfig::default()),
},
};
default_config = GlobalWalletConfig {
members: Some(GlobalWalletConfigMembers {
config_file_version,
wallet,
tor,
logging,
}),
..default_config
};
let mut config_file_name = PathBuf::from(self.data_dir.clone());
config_file_name.push(file_name);
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
if config_file_name.exists() && data_dir_name.exists() {
let msg = format!(
"{} already exists in the target directory ({}). Please remove it first",
file_name,
config_file_name.to_str().unwrap()
);
return Err(Error::Lifecycle(msg));
}
// If config exists but the datadir return ok
if config_file_name.exists() {
return Ok(());
}
// default settings are updated if no config was provided, no support for top_dir/here
let mut abs_path_node = std::env::current_dir()?;
abs_path_node.push(self.data_dir.clone());
let mut absolute_path_wallet = std::env::current_dir()?;
absolute_path_wallet.push(self.data_dir.clone());
// if no config provided, update defaults
if update == true {
// create top level dir if it doesn't exist
let dd = PathBuf::from(self.data_dir.clone());
if !dd.exists() {
// try create
fs::create_dir_all(dd)?;
default_config.update_paths(&abs_path_node, &absolute_path_wallet);
}
};
let res =
default_config.write_to_file(config_file_name.to_str().unwrap(), false, None, None);
if let Err(e) = res {
let msg = format!(
"Error creating config file as ({}): {}",
config_file_name.to_str().unwrap(),
e
);
return Err(Error::Lifecycle(msg));
}
info!(
"File {} configured and created",
config_file_name.to_str().unwrap(),
);
let mut api_secret_path = PathBuf::from(self.data_dir.clone());
api_secret_path.push(PathBuf::from(config::API_SECRET_FILE_NAME));
if !api_secret_path.exists() {
config::init_api_secret(&api_secret_path).unwrap();
} else {
config::check_api_secret(&api_secret_path).unwrap();
}
Ok(())
}
fn create_wallet(
&mut self,
_name: Option<&str>,
mnemonic: Option<ZeroingString>,
mnemonic_length: usize,
password: ZeroingString,
test_mode: bool,
) -> Result<(), Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = fmt_path((data_dir_name.to_str().unwrap()).to_string());
let exists = WalletSeed::seed_file_exists(&data_dir_name);
if !test_mode {
if let Ok(true) = exists {
let msg = format!("Wallet seed already exists at4565: {}", data_dir_name);
return Err(Error::WalletSeedExists(msg));
}
}
WalletSeed::init_file(
&data_dir_name,
mnemonic_length,
mnemonic.clone(),
password,
test_mode,
)
.map_err(|_| {
Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned())
})?;
info!("Wallet seed file created");
let mut wallet: LMDBBackend<'a, C, K> =
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
Err(e) => {
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name);
error!("{}", msg);
return Err(Error::Lifecycle(msg).into());
}
Ok(d) => d,
};
// Save init status of this wallet, to determine whether it needs a full UTXO scan
let mut batch = wallet.batch_no_mask()?;
match mnemonic {
Some(_) => batch.save_init_status(WalletInitStatus::InitNeedsScanning)?,
None => batch.save_init_status(WalletInitStatus::InitNoScanning)?,
};
batch.commit()?;
info!("Wallet database backend created at {}", data_dir_name);
Ok(())
}
fn open_wallet(
&mut self,
_name: Option<&str>,
password: ZeroingString,
create_mask: bool,
use_test_rng: bool,
) -> Result<Option<SecretKey>, Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = fmt_path(data_dir_name.to_str().unwrap().to_string());
let mut wallet: LMDBBackend<'a, C, K> =
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
Err(e) => {
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name);
return Err(Error::Lifecycle(msg));
}
Ok(d) => d,
};
let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| {
Error::Lifecycle("Error opening wallet (is password correct?)".to_owned())
})?;
let keychain = wallet_seed
.derive_keychain(global::is_testnet())
.map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?;
let mask = wallet.set_keychain(Box::new(keychain), create_mask, use_test_rng)?;
self.backend = Some(Box::new(wallet));
Ok(mask)
}
fn close_wallet(&mut self, _name: Option<&str>) -> Result<(), Error> {
if let Some(b) = self.backend.as_mut() {
b.close()?
}
self.backend = None;
Ok(())
}
fn wallet_exists(&self, _name: Option<&str>) -> Result<bool, Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = data_dir_name.to_str().unwrap();
let res = WalletSeed::seed_file_exists(&data_dir_name)
.map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?;
Ok(res)
}
fn get_mnemonic(
&self,
_name: Option<&str>,
password: ZeroingString,
) -> Result<ZeroingString, Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = fmt_path(data_dir_name.display().to_string());
let wallet_seed = WalletSeed::from_file(&data_dir_name, password)
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
let res = wallet_seed
.to_mnemonic()
.map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?;
Ok(ZeroingString::from(res))
}
fn validate_mnemonic(&self, mnemonic: ZeroingString) -> Result<(), Error> {
match WalletSeed::from_mnemonic(mnemonic) {
Ok(_) => Ok(()),
Err(_) => Err(Error::GenericError("Validating mnemonic".into())),
}
}
fn recover_from_mnemonic(
&self,
mnemonic: ZeroingString,
password: ZeroingString,
) -> Result<(), Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = data_dir_name.to_str().unwrap();
WalletSeed::recover_from_phrase(data_dir_name, mnemonic, password)
.map_err(|_| Error::Lifecycle("Error recovering from mnemonic".into()))?;
Ok(())
}
fn change_password(
&self,
_name: Option<&str>,
old: ZeroingString,
new: ZeroingString,
) -> Result<(), Error> {
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
data_dir_name.push(GRIN_WALLET_DIR);
let data_dir_name = data_dir_name.to_str().unwrap();
// get seed for later check
let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old)
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
let orig_mnemonic = orig_wallet_seed
.to_mnemonic()
.map_err(|_| Error::Lifecycle("Error recovering mnemonic".into()))?;
// Back up existing seed, and keep track of filename as we're deleting it
// once the password change is confirmed
let backup_name = WalletSeed::backup_seed(data_dir_name)
.map_err(|_| Error::Lifecycle("Error temporarily backing up existing seed".into()))?;
// Delete seed file
WalletSeed::delete_seed_file(data_dir_name).map_err(|_| {
Error::Lifecycle("Unable to delete seed file for password change".into())
})?;
// Init a new file
let _ = WalletSeed::init_file(
data_dir_name,
0,
Some(ZeroingString::from(orig_mnemonic)),
new.clone(),
false,
);
info!("Wallet seed file created");
let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new)
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
if orig_wallet_seed != new_wallet_seed {
let msg =
"New and Old wallet seeds are not equal on password change, not removing backups."
.to_string();
return Err(Error::Lifecycle(msg));
}
// Removin
info!("Password change confirmed, removing old seed file.");
fs::remove_file(backup_name).map_err(|e| Error::IO(e.to_string()))?;
Ok(())
}
fn delete_wallet(&self, _name: Option<&str>) -> Result<(), Error> {
let data_dir_name = PathBuf::from(self.data_dir.clone());
warn!(
"Removing all wallet data from: {}",
data_dir_name.to_str().unwrap()
);
fs::remove_dir_all(data_dir_name).map_err(|e| Error::IO(e.to_string()))?;
Ok(())
}
fn wallet_inst(&mut self) -> Result<&mut Box<dyn WalletBackend<'a, C, K> + 'a>, Error> {
match self.backend.as_mut() {
None => {
let msg = "Wallet has not been opened".into();
Err(Error::Lifecycle(msg))
}
Some(_) => Ok(&mut *self.backend.as_mut().unwrap()),
}
}
}
-18
View File
@@ -1,18 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod default;
mod seed;
pub use self::default::DefaultLCProvider;
-385
View File
@@ -1,385 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::blake2;
use core::num::NonZeroU32;
use rand::{thread_rng, Rng};
use serde_json;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::Path;
use std::path::MAIN_SEPARATOR;
use ring::aead;
use ring::pbkdf2;
use crate::keychain::{mnemonic, Keychain};
use crate::util::{self, ToHex};
use crate::Error;
pub const SEED_FILE: &str = "wallet.seed";
#[derive(Clone, Debug, PartialEq)]
pub struct WalletSeed(Vec<u8>);
impl WalletSeed {
pub fn from_bytes(bytes: &[u8]) -> WalletSeed {
WalletSeed(bytes.to_vec())
}
pub fn from_mnemonic(word_list: util::ZeroingString) -> Result<WalletSeed, Error> {
let res = mnemonic::to_entropy(&word_list);
match res {
Ok(s) => Ok(WalletSeed::from_bytes(&s)),
Err(_) => Err(Error::Mnemonic.into()),
}
}
pub fn _from_hex(hex: &str) -> Result<WalletSeed, Error> {
let bytes = util::from_hex(&hex.to_string())
.map_err(|_| Error::GenericError("Invalid hex".to_owned()))?;
Ok(WalletSeed::from_bytes(&bytes))
}
pub fn _to_hex(&self) -> String {
self.0.to_vec().to_hex()
}
// Helper fuction to format paths according to OS, avoids bugs on Linux
pub fn fmt_path(path: String) -> String {
let sep = &MAIN_SEPARATOR.to_string();
let path = path.replace("/", &sep);
let path = path.replace("\\", &sep);
path
}
pub fn to_mnemonic(&self) -> Result<String, Error> {
let result = mnemonic::from_entropy(&self.0);
match result {
Ok(r) => Ok(r),
Err(_) => Err(Error::Mnemonic.into()),
}
}
pub fn _derive_keychain_old(old_wallet_seed: [u8; 32], password: &str) -> Vec<u8> {
let seed = blake2::blake2b::blake2b(64, password.as_bytes(), &old_wallet_seed);
seed.as_bytes().to_vec()
}
pub fn derive_keychain<K: Keychain>(&self, is_testnet: bool) -> Result<K, Error> {
let result = K::from_seed(&self.0, is_testnet)?;
Ok(result)
}
pub fn init_new(
seed_length: usize,
test_mode: bool,
password: Option<util::ZeroingString>,
) -> WalletSeed {
let mut seed: Vec<u8> = vec![];
let mut rng = thread_rng();
if !test_mode {
for _ in 0..seed_length {
seed.push(rng.gen());
}
} else {
// Hash password and use for test seed so we have a way of keeping test wallets unique
// but predictable
seed = blake2::blake2b::blake2b(32, b"", password.unwrap().as_bytes())
.as_bytes()
.to_vec();
}
WalletSeed(seed)
}
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
let seed_file_path = &format!(
"{}{}{}",
Self::fmt_path(data_file_dir.to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
debug!("Seed file path: {}", seed_file_path);
if Path::new(seed_file_path).exists() {
Ok(true)
} else {
Ok(false)
}
}
pub fn backup_seed(data_file_dir: &str) -> Result<String, Error> {
let seed_file_name = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
let mut path = Path::new(seed_file_name).to_path_buf();
path.pop();
let mut backup_seed_file_name =
format!("{}{}{}.bak", data_file_dir, MAIN_SEPARATOR, SEED_FILE);
let mut i = 1;
while Path::new(&backup_seed_file_name).exists() {
backup_seed_file_name =
format!("{}{}{}.bak.{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE, i);
i += 1;
}
path.push(backup_seed_file_name.clone());
if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() {
return Err(Error::GenericError("Can't rename wallet seed file".to_owned()).into());
}
warn!("{} backed up as {}", seed_file_name, backup_seed_file_name);
Ok(backup_seed_file_name)
}
pub fn recover_from_phrase(
data_file_dir: &str,
word_list: util::ZeroingString,
password: util::ZeroingString,
) -> Result<(), Error> {
let seed_file_path = &format!(
"{}{}{}",
Self::fmt_path(data_file_dir.to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
debug!("data file dir: {}", data_file_dir);
if let Ok(true) = WalletSeed::seed_file_exists(data_file_dir) {
debug!("seed file exists");
WalletSeed::backup_seed(data_file_dir)?;
}
if !Path::new(&data_file_dir).exists() {
return Err(Error::WalletDoesntExist(
data_file_dir.to_owned(),
"To create a new wallet from a recovery phrase, use 'grin-wallet init -r'"
.to_owned(),
)
.into());
}
let seed = WalletSeed::from_mnemonic(word_list)?;
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
file.write_all(&enc_seed_json.as_bytes())
.map_err(|_| Error::IO)?;
warn!("Seed created from word list");
Ok(())
}
pub fn init_file(
data_file_dir: &str,
seed_length: usize,
recovery_phrase: Option<util::ZeroingString>,
password: util::ZeroingString,
test_mode: bool,
) -> Result<WalletSeed, Error> {
// create directory if it doesn't exist
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
let seed_file_path = &format!(
"{}{}{}",
Self::fmt_path(data_file_dir.to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
let data_file_dir = Self::fmt_path(data_file_dir.to_string());
warn!("Generating wallet seed file at: {}", seed_file_path);
let exists = WalletSeed::seed_file_exists(&data_file_dir)?;
if exists && !test_mode {
let msg = format!("Wallet seed already exists at: {}", data_file_dir);
error!("{}", msg);
return Err(Error::WalletSeedExists(msg));
}
let seed = match recovery_phrase {
Some(p) => WalletSeed::from_mnemonic(p)?,
None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())),
};
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
file.write_all(&enc_seed_json.as_bytes())
.map_err(|_| Error::IO)?;
Ok(seed)
}
pub fn from_file(
data_file_dir: &str,
password: util::ZeroingString,
) -> Result<WalletSeed, Error> {
// create directory if it doesn't exist
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
let seed_file_path = &format!(
"{}{}{}",
Self::fmt_path(data_file_dir.to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
debug!("Using wallet seed file at: {}", seed_file_path);
if Path::new(seed_file_path).exists() {
let mut file = File::open(seed_file_path).map_err(|_| Error::IO)?;
let mut buffer = String::new();
file.read_to_string(&mut buffer).map_err(|_| Error::IO)?;
let enc_seed: EncryptedWalletSeed =
serde_json::from_str(&buffer).map_err(|_| Error::Format)?;
let wallet_seed = enc_seed.decrypt(&password)?;
Ok(wallet_seed)
} else {
error!(
"wallet seed file {} could not be opened (grin-wallet init). \
Run \"grin-wallet init\" to initialize a new wallet.",
seed_file_path
);
Err(Error::WalletSeedDoesntExist)
}
}
pub fn delete_seed_file(data_file_dir: &str) -> Result<(), Error> {
let seed_file_path = &format!(
"{}{}{}",
Self::fmt_path(data_file_dir.to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
if Path::new(seed_file_path).exists() {
debug!("Deleting wallet seed file at: {}", seed_file_path);
fs::remove_file(seed_file_path).map_err(|_| Error::IO)?;
}
Ok(())
}
}
/// Encrypted wallet seed, for storing on disk and decrypting
/// with provided password
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct EncryptedWalletSeed {
encrypted_seed: String,
/// Salt, not so useful in single case but include anyhow for situations
/// where someone wants to store many of these
pub salt: String,
/// Nonce
pub nonce: String,
}
impl EncryptedWalletSeed {
/// Create a new encrypted seed from the given seed + password
pub fn from_seed(
seed: &WalletSeed,
password: util::ZeroingString,
) -> Result<EncryptedWalletSeed, Error> {
let salt: [u8; 8] = thread_rng().gen();
let nonce: [u8; 12] = thread_rng().gen();
let password = password.as_bytes();
let mut key = [0; 32];
pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA512,
NonZeroU32::new(100).unwrap(),
&salt,
password,
&mut key,
);
let content = seed.0.to_vec();
let mut enc_bytes = content;
/*let suffix_len = aead::CHACHA20_POLY1305.tag_len();
for _ in 0..suffix_len {
enc_bytes.push(0);
}*/
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
let sealing_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
let aad = aead::Aad::from(&[]);
let res = sealing_key.seal_in_place_append_tag(
aead::Nonce::assume_unique_for_key(nonce),
aad,
&mut enc_bytes,
);
if let Err(_) = res {
return Err(Error::Encryption);
}
Ok(EncryptedWalletSeed {
encrypted_seed: enc_bytes.to_hex(),
salt: salt.to_hex(),
nonce: nonce.to_hex(),
})
}
/// Decrypt seed
pub fn decrypt(&self, password: &str) -> Result<WalletSeed, Error> {
let mut encrypted_seed = match util::from_hex(&self.encrypted_seed.clone()) {
Ok(s) => s,
Err(_) => return Err(Error::Encryption),
};
let salt = match util::from_hex(&self.salt.clone()) {
Ok(s) => s,
Err(_) => return Err(Error::Encryption),
};
let nonce = match util::from_hex(&self.nonce.clone()) {
Ok(s) => s,
Err(_) => return Err(Error::Encryption),
};
let password = password.as_bytes();
let mut key = [0; 32];
pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA512,
NonZeroU32::new(100).unwrap(),
&salt,
password,
&mut key,
);
let mut n = [0u8; 12];
n.copy_from_slice(&nonce[0..12]);
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
let opening_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
let aad = aead::Aad::from(&[]);
let res = opening_key.open_in_place(
aead::Nonce::assume_unique_for_key(n),
aad,
&mut encrypted_seed,
);
if let Err(_) = res {
return Err(Error::Encryption);
}
for _ in 0..aead::AES_256_GCM.tag_len() {
encrypted_seed.pop();
}
Ok(WalletSeed::from_bytes(&encrypted_seed))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util::ZeroingString;
#[test]
fn wallet_seed_encrypt() {
let password = ZeroingString::from("passwoid");
let wallet_seed = WalletSeed::init_new(32, false, None);
let mut enc_wallet_seed =
EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap();
println!("EWS: {:?}", enc_wallet_seed);
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password).unwrap();
assert_eq!(wallet_seed, decrypted_wallet_seed);
// Wrong password
let decrypted_wallet_seed = enc_wallet_seed.decrypt("");
assert!(decrypted_wallet_seed.is_err());
// Wrong nonce
enc_wallet_seed.nonce = "wrongnonce".to_owned();
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password);
assert!(decrypted_wallet_seed.is_err());
}
}