Merge milestone/2.1.0 into master (#199)

* version bump for next potential release

* Merge master into milestone/2.1.0 (#182)

* Derive --version output dynamically from cargo package version (#174)

* add --txid to the `wallet txs` command (#176)

* add --txid to the `wallet txs` command

* add test for `wallet txs` command with `--txid` parameter

* Refactor - Split WalletCommAdapter into multiple traits (#180)

* Derive --version output dynamically from cargo package version (#174)

* add server auth argument to http client

* Revert "add server auth argument to http client"

This reverts commit f52a8d2c7cdfb8583af5716ad621eb560811d6ee.

* modify WalletCommAdapter, moving dest argument into fields on implementors,
visiting havok on automated tests, at least one of which is now out of date and failing

* Split WalletCommAdapter into four traits, one for each of its intended behaviors.

* Remove two vestigals
1. args, a stringly typed argument to put_tx
2. NullAdapter, which is no longer used

* Remove unused "params" argument from listen method.

* Re-add previously existing TODO comment

* Fix non-test build

* completely Fix non-test build

* Full Lifecycle API Support (#184)

* refactoring wallet lib traits

* rustfmt

* rustfmt

* add new files

* explicit lifetime specifiers on all wallet traits

* rustfmt

* modify apis to use new walletinst

* rustfmt

* converting controller crate

* rustfmt

* controller crate compiling

* rustfmt

* compilation

* rustfmt

* Remove config from wallet, implement open_wallet, close_wallet in lifecycle provider, remove password + open_with_credentials from WalletBackend + impl

* rustfmt

* full compilation, changing recovery + init to new model

* rustfmt

* wallet initialisation working, init command output and flow identical to v2.0.0 wallet

* rustfmt

* fix listener and owner api startup

* rustfmt

* rustfmt

* move encryption test

* rustfmt

* fix api doctests

* rustfmt

* fix for most tests in controller crate

* rustfmt

* fix for check tests in controller crate

* fix main wallet tests

* rustfmt

* add explicit functions to handle mnemonic recovery, fix CLI recovery workflow

* rustfmt

* update keybase adapter to use new wallet format

* rustfmt

* test fix

* remove debug output
This commit is contained in:
Yeastplume
2019-07-29 13:25:03 +01:00
committed by GitHub
parent 7b6d597d39
commit c40e8a915b
54 changed files with 2405 additions and 1942 deletions
+230
View File
@@ -0,0 +1,230 @@
// Copyright 2019 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, GRIN_WALLET_DIR};
use crate::core::global;
use crate::keychain::Keychain;
use crate::libwallet::{Error, ErrorKind, NodeClient, WalletBackend, WalletLCProvider};
use crate::lifecycle::seed::WalletSeed;
use crate::util::ZeroingString;
use crate::LMDBBackend;
use failure::ResultExt;
use std::path::PathBuf;
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_wallet_directory(&mut self, dir: &str) {
self.data_dir = dir.to_owned();
}
fn create_config(&self, chain_type: &global::ChainTypes, file_name: &str) -> Result<(), Error> {
let mut default_config = GlobalWalletConfig::for_chain(chain_type);
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(ErrorKind::Lifecycle(msg).into());
}
// just leave as is if file exists but there's no data dir
if config_file_name.exists() {
return Ok(());
}
default_config.update_paths(&PathBuf::from(self.data_dir.clone()));
let res = default_config.write_to_file(config_file_name.to_str().unwrap());
if let Err(e) = res {
let msg = format!(
"Error creating config file as ({}): {}",
config_file_name.to_str().unwrap(),
e
);
return Err(ErrorKind::Lifecycle(msg).into());
}
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,
) -> 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();
let _ = WalletSeed::init_file(&data_dir_name, mnemonic_length, mnemonic, password);
info!("Wallet seed file created");
let _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);
return Err(ErrorKind::Lifecycle(msg).into());
}
Ok(d) => d,
};
info!("Wallet database backend created at {}", data_dir_name);
Ok(())
}
fn open_wallet(&mut self, _name: Option<&str>, 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();
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(ErrorKind::Lifecycle(msg).into());
}
Ok(d) => d,
};
let wallet_seed = WalletSeed::from_file(&data_dir_name, password)
.context(ErrorKind::Lifecycle("Error opening wallet".into()))?;
let keychain = wallet_seed
.derive_keychain(global::is_floonet())
.context(ErrorKind::Lifecycle("Error deriving keychain".into()))?;
wallet.set_keychain(Box::new(keychain));
self.backend = Some(Box::new(wallet));
Ok(())
}
fn close_wallet(&mut self, _name: Option<&str>) -> Result<(), Error> {
match self.backend.as_mut() {
Some(b) => b.close()?,
None => {}
};
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).context(ErrorKind::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 = data_dir_name.to_str().unwrap();
let wallet_seed = WalletSeed::from_file(&data_dir_name, password).context(
ErrorKind::Lifecycle("Error opening wallet seed file".into()),
)?;
let res = wallet_seed
.to_mnemonic()
.context(ErrorKind::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(ErrorKind::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).context(
ErrorKind::Lifecycle("Error recovering from mnemonic".into()),
)?;
Ok(())
}
fn change_password(&self, _old: String, _new: String) -> Result<(), Error> {
unimplemented!()
}
fn delete_wallet(&self, _name: Option<String>, _password: String) -> Result<(), Error> {
unimplemented!()
}
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(ErrorKind::Lifecycle(msg).into())
}
Some(_) => Ok(&mut *self.backend.as_mut().unwrap()),
}
}
}
+18
View File
@@ -0,0 +1,18 @@
// Copyright 2019 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;
+297
View File
@@ -0,0 +1,297 @@
// Copyright 2018 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 std::fs::{self, File};
use std::io::{Read, Write};
use std::path::Path;
use std::path::MAIN_SEPARATOR;
use crate::blake2;
use rand::{thread_rng, Rng};
use serde_json;
use ring::aead;
use ring::{digest, pbkdf2};
use crate::keychain::{mnemonic, Keychain};
use crate::util;
use crate::{Error, ErrorKind};
use failure::ResultExt;
pub const SEED_FILE: &'static 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(ErrorKind::Mnemonic.into()),
}
}
pub fn _from_hex(hex: &str) -> Result<WalletSeed, Error> {
let bytes = util::from_hex(hex.to_string())
.context(ErrorKind::GenericError("Invalid hex".to_owned()))?;
Ok(WalletSeed::from_bytes(&bytes))
}
pub fn _to_hex(&self) -> String {
util::to_hex(self.0.to_vec())
}
pub fn to_mnemonic(&self) -> Result<String, Error> {
let result = mnemonic::from_entropy(&self.0);
match result {
Ok(r) => Ok(r),
Err(_) => Err(ErrorKind::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_floonet: bool) -> Result<K, Error> {
let result = K::from_seed(&self.0, is_floonet)?;
Ok(result)
}
pub fn init_new(seed_length: usize) -> WalletSeed {
let mut seed: Vec<u8> = vec![];
let mut rng = thread_rng();
for _ in 0..seed_length {
seed.push(rng.gen());
}
WalletSeed(seed)
}
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
let seed_file_path = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
println!("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<(), 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 let Err(_) = fs::rename(seed_file_name, backup_seed_file_name.as_str()) {
return Err(ErrorKind::GenericError(
"Can't rename wallet seed file".to_owned(),
))?;
}
warn!("{} backed up as {}", seed_file_name, backup_seed_file_name);
Ok(())
}
pub fn recover_from_phrase(
data_file_dir: &str,
word_list: util::ZeroingString,
password: util::ZeroingString,
) -> Result<(), Error> {
let seed_file_path = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
println!("data file dir: {}", data_file_dir);
if let Ok(true) = WalletSeed::seed_file_exists(data_file_dir) {
println!("seed file exists");
WalletSeed::backup_seed(data_file_dir)?;
}
if !Path::new(&data_file_dir).exists() {
return Err(ErrorKind::WalletDoesntExist(
data_file_dir.to_owned(),
"To create a new wallet from a recovery phrase, use 'grin-wallet init -r'"
.to_owned(),
))?;
}
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).context(ErrorKind::Format)?;
let mut file = File::create(seed_file_path).context(ErrorKind::IO)?;
file.write_all(&enc_seed_json.as_bytes())
.context(ErrorKind::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,
) -> Result<WalletSeed, Error> {
// create directory if it doesn't exist
fs::create_dir_all(data_file_dir).context(ErrorKind::IO)?;
let seed_file_path = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
warn!("Generating wallet seed file at: {}", seed_file_path);
let _ = WalletSeed::seed_file_exists(data_file_dir)?;
let seed = match recovery_phrase {
Some(p) => WalletSeed::from_mnemonic(p)?,
None => WalletSeed::init_new(seed_length),
};
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).context(ErrorKind::Format)?;
let mut file = File::create(seed_file_path).context(ErrorKind::IO)?;
file.write_all(&enc_seed_json.as_bytes())
.context(ErrorKind::IO)?;
Ok(seed)
}
pub fn from_file(
data_file_dir: &str,
password: util::ZeroingString,
) -> Result<WalletSeed, Error> {
// TODO: Is this desirable any more?
// create directory if it doesn't exist
fs::create_dir_all(data_file_dir).context(ErrorKind::IO)?;
let seed_file_path = &format!("{}{}{}", data_file_dir, 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).context(ErrorKind::IO)?;
let mut buffer = String::new();
file.read_to_string(&mut buffer).context(ErrorKind::IO)?;
let enc_seed: EncryptedWalletSeed =
serde_json::from_str(&buffer).context(ErrorKind::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(ErrorKind::WalletSeedDoesntExist)?
}
}
}
/// 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(&digest::SHA512, 100, &salt, password, &mut key);
let content = seed.0.to_vec();
let mut enc_bytes = content.clone();
let suffix_len = aead::CHACHA20_POLY1305.tag_len();
for _ in 0..suffix_len {
enc_bytes.push(0);
}
let sealing_key =
aead::SealingKey::new(&aead::CHACHA20_POLY1305, &key).context(ErrorKind::Encryption)?;
aead::seal_in_place(&sealing_key, &nonce, &[], &mut enc_bytes, suffix_len)
.context(ErrorKind::Encryption)?;
Ok(EncryptedWalletSeed {
encrypted_seed: util::to_hex(enc_bytes.to_vec()),
salt: util::to_hex(salt.to_vec()),
nonce: util::to_hex(nonce.to_vec()),
})
}
/// 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(ErrorKind::Encryption)?,
};
let salt = match util::from_hex(self.salt.clone()) {
Ok(s) => s,
Err(_) => return Err(ErrorKind::Encryption)?,
};
let nonce = match util::from_hex(self.nonce.clone()) {
Ok(s) => s,
Err(_) => return Err(ErrorKind::Encryption)?,
};
let password = password.as_bytes();
let mut key = [0; 32];
pbkdf2::derive(&digest::SHA512, 100, &salt, password, &mut key);
let opening_key =
aead::OpeningKey::new(&aead::CHACHA20_POLY1305, &key).context(ErrorKind::Encryption)?;
let decrypted_data = aead::open_in_place(&opening_key, &nonce, &[], 0, &mut encrypted_seed)
.context(ErrorKind::Encryption)?;
Ok(WalletSeed::from_bytes(&decrypted_data))
}
}
#[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);
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());
}
}