use std::{collections::HashSet, fs, path::Path};
use crate::{
accounts_dir::{
DiskKeyFileManager, KeyDirectory, KeyFileManager, RootDiskDirectory,
},
Error,
};
use cfxkey::Address;
use dir;
pub fn import_account(
path: &Path, dst: &dyn KeyDirectory,
) -> Result<Address, Error> {
let key_manager = DiskKeyFileManager::default();
let existing_accounts = dst
.load()?
.into_iter()
.map(|a| a.address)
.collect::<HashSet<_>>();
let filename = path
.file_name()
.and_then(|n| n.to_str())
.map(|f| f.to_owned());
let account = fs::File::open(&path)
.map_err(Into::into)
.and_then(|file| key_manager.read(filename, file))?;
let address = account.address.clone();
if !existing_accounts.contains(&address) {
dst.insert(account)?;
}
Ok(address)
}
pub fn import_accounts(
src: &dyn KeyDirectory, dst: &dyn KeyDirectory,
) -> Result<Vec<Address>, Error> {
let accounts = src.load()?;
let existing_accounts = dst
.load()?
.into_iter()
.map(|a| a.address)
.collect::<HashSet<_>>();
accounts
.into_iter()
.filter(|a| !existing_accounts.contains(&a.address))
.map(|a| {
let address = a.address.clone();
dst.insert(a)?;
Ok(address)
})
.collect()
}
pub fn read_geth_accounts(testnet: bool) -> Vec<Address> {
RootDiskDirectory::at(dir::geth(testnet))
.load()
.map(|d| d.into_iter().map(|a| a.address).collect())
.unwrap_or_else(|_| Vec::new())
}
pub fn import_geth_accounts(
dst: &dyn KeyDirectory, desired: HashSet<Address>, testnet: bool,
) -> Result<Vec<Address>, Error> {
let src = RootDiskDirectory::at(dir::geth(testnet));
let accounts = src.load()?;
let existing_accounts = dst
.load()?
.into_iter()
.map(|a| a.address)
.collect::<HashSet<_>>();
accounts
.into_iter()
.filter(|a| !existing_accounts.contains(&a.address))
.filter(|a| desired.contains(&a.address))
.map(|a| {
let address = a.address.clone();
dst.insert(a)?;
Ok(address)
})
.collect()
}