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
+243 -186
View File
@@ -12,31 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Grin wallet command-line function implementations
use crate::api::TLSConfig;
use crate::config::{WalletConfig, WALLET_CONFIG_FILE_NAME};
use crate::core::{core, global};
use crate::error::{Error, ErrorKind};
use crate::impls::{create_sender, KeybaseAllChannels, SlateGetter as _, SlateReceiver as _};
use crate::impls::{PathToSlate, SlatePutter};
use crate::keychain;
use crate::libwallet::{InitTxArgs, IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider};
use crate::util::{Mutex, ZeroingString};
use std::collections::HashMap;
/// Grin wallet command-line function implementations
use crate::{controller, display};
use serde_json as json;
use std::fs::File;
use std::io::Write;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use serde_json as json;
use uuid::Uuid;
use crate::api::TLSConfig;
use crate::core::core;
use crate::keychain;
use crate::config::WalletConfig;
use crate::error::{Error, ErrorKind};
use crate::impls::{
instantiate_wallet, FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter,
LMDBBackend, NullWalletCommAdapter,
};
use crate::impls::{HTTPNodeClient, WalletSeed};
use crate::libwallet::{InitTxArgs, IssueInvoiceTxArgs, NodeClient, WalletInst};
use crate::{controller, display};
fn show_recovery_phrase(phrase: ZeroingString) {
println!("Your recovery phrase is:");
println!();
println!("{}", &*phrase);
println!();
println!("Please back-up these words in a non-digital format.");
}
/// Arguments common to all wallet commands
#[derive(Clone)]
@@ -44,6 +46,7 @@ pub struct GlobalArgs {
pub account: String,
pub node_api_secret: Option<String>,
pub show_spent: bool,
pub chain_type: global::ChainTypes,
pub password: Option<ZeroingString>,
pub tls_conf: Option<TLSConfig>,
}
@@ -58,21 +61,28 @@ pub struct InitArgs {
pub restore: bool,
}
pub fn init(g_args: &GlobalArgs, args: InitArgs) -> Result<(), Error> {
WalletSeed::init_file(
&args.config,
args.list_length,
pub fn init<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
g_args: &GlobalArgs,
args: InitArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
let mut w_lock = wallet.lock();
let p = w_lock.lc_provider()?;
p.create_config(&g_args.chain_type, WALLET_CONFIG_FILE_NAME)?;
p.create_wallet(
None,
args.recovery_phrase,
&args.password,
args.list_length,
args.password.clone(),
)?;
info!("Wallet seed file created");
let client_n = HTTPNodeClient::new(
&args.config.check_node_api_http_addr,
g_args.node_api_secret.clone(),
);
let _: LMDBBackend<HTTPNodeClient, keychain::ExtKeychain> =
LMDBBackend::new(args.config.clone(), &args.password, client_n)?;
info!("Wallet database backend created");
let m = p.get_mnemonic(None, args.password)?;
show_recovery_phrase(m);
Ok(())
}
@@ -82,30 +92,23 @@ pub struct RecoverArgs {
pub passphrase: ZeroingString,
}
/// Check whether seed file exists
pub fn wallet_seed_exists(config: &WalletConfig) -> Result<(), Error> {
let res = WalletSeed::seed_file_exists(&config)?;
Ok(res)
}
pub fn recover(config: &WalletConfig, args: RecoverArgs) -> Result<(), Error> {
if args.recovery_phrase.is_none() {
let res = WalletSeed::from_file(config, &args.passphrase);
if let Err(e) = res {
error!("Error loading wallet seed (check password): {}", e);
return Err(e.into());
}
let _ = res.unwrap().show_recovery_phrase();
} else {
let res = WalletSeed::recover_from_phrase(
&config,
&args.recovery_phrase.as_ref().unwrap(),
&args.passphrase,
);
if let Err(e) = res {
error!("Error recovering seed - {}", e);
return Err(e.into());
pub fn recover<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: RecoverArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
let mut w_lock = wallet.lock();
let p = w_lock.lc_provider()?;
match args.recovery_phrase {
None => {
let m = p.get_mnemonic(None, args.passphrase)?;
show_recovery_phrase(m);
}
Some(phrase) => p.recover_from_mnemonic(phrase, args.passphrase)?,
}
Ok(())
}
@@ -115,49 +118,36 @@ pub struct ListenArgs {
pub method: String,
}
pub fn listen(config: &WalletConfig, args: &ListenArgs, g_args: &GlobalArgs) -> Result<(), Error> {
let mut params = HashMap::new();
params.insert("api_listen_addr".to_owned(), config.api_listen_addr());
if let Some(t) = g_args.tls_conf.as_ref() {
params.insert("certificate".to_owned(), t.certificate.clone());
params.insert("private_key".to_owned(), t.private_key.clone());
}
pub fn listen<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
config: &WalletConfig,
args: &ListenArgs,
g_args: &GlobalArgs,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let res = match args.method.as_str() {
"http" => {
// HTTP adapter can't use the listen trait method because of the
// crate structure. May be able to fix when V1 API is deprecated
let node_client = HTTPNodeClient::new(
&config.check_node_api_http_addr,
g_args.node_api_secret.clone(),
);
let wallet = instantiate_wallet(
config.clone(),
node_client,
&g_args.password.clone().unwrap(),
&g_args.account,
)?;
let listen_addr = params.get("api_listen_addr").unwrap();
let tls_conf = match params.get("certificate") {
Some(s) => Some(TLSConfig::new(
s.to_owned(),
params.get("private_key").unwrap().to_owned(),
)),
None => None,
};
controller::foreign_listener(wallet.clone(), &listen_addr, tls_conf)?;
Ok(())
"http" => controller::foreign_listener(
wallet.clone(),
&config.api_listen_addr(),
g_args.tls_conf.clone(),
),
"keybase" => KeybaseAllChannels::new()?.listen(
config.clone(),
g_args.password.clone().unwrap(),
&g_args.account,
g_args.node_api_secret.clone(),
),
method => {
return Err(ErrorKind::ArgumentError(format!(
"No listener for method \"{}\".",
method
))
.into());
}
"keybase" => {
let adapter = KeybaseWalletCommAdapter::new();
adapter.listen(
params,
config.clone(),
&g_args.password.clone().unwrap(),
&g_args.account,
g_args.node_api_secret.clone(),
)
}
_ => Ok(()),
};
if let Err(e) = res {
@@ -166,11 +156,16 @@ pub fn listen(config: &WalletConfig, args: &ListenArgs, g_args: &GlobalArgs) ->
Ok(())
}
pub fn owner_api(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn owner_api<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
config: &WalletConfig,
g_args: &GlobalArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + Send + Sync + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let res = controller::owner_listener(
wallet,
config.owner_api_listen_addr().as_str(),
@@ -189,10 +184,15 @@ pub struct AccountArgs {
pub create: Option<String>,
}
pub fn account(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn account<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: AccountArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
if args.create.is_none() {
let res = controller::owner_single_use(wallet, |api| {
let acct_mappings = api.accounts()?;
@@ -237,11 +237,16 @@ pub struct SendArgs {
pub target_slate_version: Option<u16>,
}
pub fn send(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn send<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: SendArgs,
dark_scheme: bool,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
if args.estimate_selection_strategies {
let strategies = vec!["smallest", "all"]
@@ -291,42 +296,41 @@ pub fn send(
return Err(e);
}
};
let adapter = match args.method.as_str() {
"http" => HTTPWalletCommAdapter::new(),
"file" => FileWalletCommAdapter::new(),
"keybase" => KeybaseWalletCommAdapter::new(),
"self" => NullWalletCommAdapter::new(),
_ => NullWalletCommAdapter::new(),
};
if adapter.supports_sync() {
slate = adapter.send_tx_sync(&args.dest, &slate)?;
api.tx_lock_outputs(&slate, 0)?;
if args.method == "self" {
match args.method.as_str() {
"file" => {
PathToSlate((&args.dest).into()).put_tx(&slate)?;
api.tx_lock_outputs(&slate, 0)?;
return Ok(());
}
"self" => {
api.tx_lock_outputs(&slate, 0)?;
controller::foreign_single_use(wallet, |api| {
slate = api.receive_tx(&slate, Some(&args.dest), None)?;
Ok(())
})?;
}
if let Err(e) = api.verify_slate_messages(&slate) {
error!("Error validating participant messages: {}", e);
return Err(e);
method => {
let sender = create_sender(method, &args.dest)?;
slate = sender.send_tx(&slate)?;
api.tx_lock_outputs(&slate, 0)?;
}
slate = api.finalize_tx(&slate)?;
} else {
adapter.send_tx_async(&args.dest, &slate)?;
api.tx_lock_outputs(&slate, 0)?;
}
if adapter.supports_sync() {
let result = api.post_tx(&slate.tx, args.fluff);
match result {
Ok(_) => {
info!("Tx sent ok",);
return Ok(());
}
Err(e) => {
error!("Tx sent fail: {}", e);
return Err(e);
}
api.verify_slate_messages(&slate).map_err(|e| {
error!("Error validating participant messages: {}", e);
e
})?;
slate = api.finalize_tx(&slate)?;
let result = api.post_tx(&slate.tx, args.fluff);
match result {
Ok(_) => {
info!("Tx sent ok",);
return Ok(());
}
Err(e) => {
error!("Tx sent fail: {}", e);
return Err(e);
}
}
}
@@ -341,13 +345,17 @@ pub struct ReceiveArgs {
pub message: Option<String>,
}
pub fn receive(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn receive<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
g_args: &GlobalArgs,
args: ReceiveArgs,
) -> Result<(), Error> {
let adapter = FileWalletCommAdapter::new();
let mut slate = adapter.receive_tx_async(&args.input)?;
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
let mut slate = PathToSlate((&args.input).into()).get_tx()?;
controller::foreign_single_use(wallet, |api| {
if let Err(e) = api.verify_slate_messages(&slate) {
error!("Error validating participant messages: {}", e);
@@ -356,8 +364,7 @@ pub fn receive(
slate = api.receive_tx(&slate, Some(&g_args.account), args.message.clone())?;
Ok(())
})?;
let send_tx = format!("{}.response", args.input);
adapter.send_tx_async(&send_tx, &slate)?;
PathToSlate(format!("{}.response", args.input).into()).put_tx(&slate)?;
info!(
"Response file {}.response generated, and can be sent back to the transaction originator.",
args.input
@@ -371,12 +378,17 @@ pub struct FinalizeArgs {
pub fluff: bool,
}
pub fn finalize(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn finalize<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: FinalizeArgs,
) -> Result<(), Error> {
let adapter = FileWalletCommAdapter::new();
let mut slate = adapter.receive_tx_async(&args.input)?;
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
let mut slate = PathToSlate((&args.input).into()).get_tx()?;
// Rather than duplicating the entire command, we'll just
// try to determine what kind of finalization this is
// based on the slate contents
@@ -440,10 +452,15 @@ pub struct IssueInvoiceArgs {
pub issue_args: IssueInvoiceTxArgs,
}
pub fn issue_invoice_tx(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn issue_invoice_tx<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: IssueInvoiceArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let slate = api.issue_invoice_tx(args.issue_args)?;
let mut tx_file = File::create(args.dest.clone())?;
@@ -467,13 +484,17 @@ pub struct ProcessInvoiceArgs {
}
/// Process invoice
pub fn process_invoice(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn process_invoice<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: ProcessInvoiceArgs,
dark_scheme: bool,
) -> Result<(), Error> {
let adapter = FileWalletCommAdapter::new();
let slate = adapter.receive_tx_async(&args.input)?;
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
let slate = PathToSlate((&args.input).into()).get_tx()?;
controller::owner_single_use(wallet.clone(), |api| {
if args.estimate_selection_strategies {
let strategies = vec!["smallest", "all"]
@@ -526,24 +547,25 @@ pub fn process_invoice(
return Err(e);
}
};
let adapter = match args.method.as_str() {
"http" => HTTPWalletCommAdapter::new(),
"file" => FileWalletCommAdapter::new(),
"self" => NullWalletCommAdapter::new(),
_ => NullWalletCommAdapter::new(),
};
if adapter.supports_sync() {
slate = adapter.send_tx_sync(&args.dest, &slate)?;
api.tx_lock_outputs(&slate, 0)?;
if args.method == "self" {
match args.method.as_str() {
"file" => {
let slate_putter = PathToSlate((&args.dest).into());
slate_putter.put_tx(&slate)?;
api.tx_lock_outputs(&slate, 0)?;
}
"self" => {
api.tx_lock_outputs(&slate, 0)?;
controller::foreign_single_use(wallet, |api| {
slate = api.finalize_invoice_tx(&slate)?;
Ok(())
})?;
}
} else {
adapter.send_tx_async(&args.dest, &slate)?;
api.tx_lock_outputs(&slate, 0)?;
method => {
let sender = create_sender(method, &args.dest)?;
slate = sender.send_tx(&slate)?;
api.tx_lock_outputs(&slate, 0)?;
}
}
}
Ok(())
@@ -555,12 +577,17 @@ pub struct InfoArgs {
pub minimum_confirmations: u64,
}
pub fn info(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn info<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
g_args: &GlobalArgs,
args: InfoArgs,
dark_scheme: bool,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let (validated, wallet_info) =
api.retrieve_summary_info(true, args.minimum_confirmations)?;
@@ -570,11 +597,16 @@ pub fn info(
Ok(())
}
pub fn outputs(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn outputs<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
g_args: &GlobalArgs,
dark_scheme: bool,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let res = api.node_height()?;
let (validated, outputs) = api.retrieve_outputs(g_args.show_spent, true, None)?;
@@ -590,12 +622,17 @@ pub struct TxsArgs {
pub tx_slate_id: Option<Uuid>,
}
pub fn txs(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn txs<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
g_args: &GlobalArgs,
args: TxsArgs,
dark_scheme: bool,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let res = api.node_height()?;
let (validated, txs) = api.retrieve_txs(true, args.id, args.tx_slate_id)?;
@@ -645,10 +682,15 @@ pub struct RepostArgs {
pub fluff: bool,
}
pub fn repost(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn repost<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: RepostArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let (_, txs) = api.retrieve_txs(true, Some(args.id), None)?;
let stored_tx = api.get_stored_tx(&txs[0])?;
@@ -691,10 +733,15 @@ pub struct CancelArgs {
pub tx_id_string: String,
}
pub fn cancel(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn cancel<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: CancelArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let result = api.cancel_tx(args.tx_id, args.tx_slate_id);
match result {
@@ -711,9 +758,14 @@ pub fn cancel(
Ok(())
}
pub fn restore(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
) -> Result<(), Error> {
pub fn restore<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
let result = api.restore();
match result {
@@ -736,10 +788,15 @@ pub struct CheckArgs {
pub delete_unconfirmed: bool,
}
pub fn check_repair(
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
pub fn check_repair<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
args: CheckArgs,
) -> Result<(), Error> {
) -> Result<(), Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: keychain::Keychain + 'a,
{
controller::owner_single_use(wallet.clone(), |api| {
warn!("Starting wallet check...",);
warn!("Updating all wallet outputs, please wait ...",);