Wallet Interactive-mode, Part 1 (#295)

* cli addition to yml

* first experiments with CLI mode

* rustfmt

* modify owner_single_use to take optional instantiated API

* refactor command functions to take owner api instance

* modify commands to use single owner api instance

* add ability to pass customised message handler to API

* prevent update wallet attempt if wallet hasn't been opened

* fix output when internal updater is running

* add termion, use cli for status updates, remove logging output from CLI

* some attempts to clean up the command prompt and accomodate scanning intervals

* rework listener slightly to allow for cli mode, add close command

* remove termion dependency
This commit is contained in:
Yeastplume
2020-02-06 09:08:24 +00:00
committed by GitHub
parent 0ae921461c
commit 2d264db91a
28 changed files with 929 additions and 314 deletions
+6 -2
View File
@@ -16,7 +16,6 @@
#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
use crate::config::ConfigError;
@@ -128,7 +127,12 @@ fn real_main() -> i32 {
//config.members.as_mut().unwrap().wallet.chain_type = Some(chain_type);
// Load logging config
let l = config.members.as_mut().unwrap().logging.clone().unwrap();
let mut l = config.members.as_mut().unwrap().logging.clone().unwrap();
// no logging to stdout if we're running cli
match args.subcommand() {
("cli", _) => l.log_to_stdout = true,
_ => {}
};
init_logger(Some(l), None);
info!(
"Using wallet configuration file at {}",
+6
View File
@@ -43,6 +43,8 @@ args:
long: api_server_address
takes_value: true
subcommands:
- cli:
about: Start the wallet in interactive CLI mode (EXPERIMENTAL and UNDER DEVELOPMENT)
- account:
about: List wallet accounts or create a new account
args:
@@ -346,6 +348,10 @@ subcommands:
short: r
long: recover
takes_value: false
- open:
about: Opens a wallet (interactive mode only)
- close:
about: Closes the wallet (interactive mode only)
- recover:
about: Displays a recovery phrase for the wallet. (use `init -r` to perform recovery)
- address:
+312
View File
@@ -0,0 +1,312 @@
// Copyright 2020 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::cmd::wallet_args;
use crate::util::secp::key::SecretKey;
use crate::util::Mutex;
use clap::App;
//use colored::Colorize;
use grin_wallet_api::Owner;
use grin_wallet_config::{TorConfig, WalletConfig};
use grin_wallet_controller::command::GlobalArgs;
use grin_wallet_controller::Error;
use grin_wallet_impls::DefaultWalletImpl;
use grin_wallet_libwallet::{NodeClient, StatusMessage, WalletInst, WalletLCProvider};
use grin_wallet_util::grin_keychain as keychain;
use rustyline::completion::{Completer, FilenameCompleter, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{CompletionType, Config, Context, EditMode, Editor, Helper, OutputStreamType};
use std::borrow::Cow::{self, Borrowed, Owned};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
const COLORED_PROMPT: &'static str = "\x1b[36mgrin-wallet>\x1b[0m ";
const PROMPT: &'static str = "grin-wallet> ";
//const HISTORY_PATH: &str = ".history";
// static for keeping track of current stdin buffer contents
lazy_static! {
static ref STDIN_CONTENTS: Mutex<String> = { Mutex::new(String::from("")) };
}
#[macro_export]
macro_rules! cli_message_inline {
($fmt_string:expr, $( $arg:expr ),+) => {
{
use std::io::Write;
let contents = STDIN_CONTENTS.lock();
/* use crate::common::{is_cli, COLORED_PROMPT}; */
/* if is_cli() { */
print!("\r");
print!($fmt_string, $( $arg ),*);
print!(" {}", COLORED_PROMPT);
print!("\x1B[J");
print!("{}", *contents);
std::io::stdout().flush().unwrap();
/*} else {
info!($fmt_string, $( $arg ),*);
}*/
}
};
}
#[macro_export]
macro_rules! cli_message {
($fmt_string:expr, $( $arg:expr ),+) => {
{
use std::io::Write;
/* use crate::common::{is_cli, COLORED_PROMPT}; */
/* if is_cli() { */
//print!("\r");
print!($fmt_string, $( $arg ),*);
println!();
std::io::stdout().flush().unwrap();
/*} else {
info!($fmt_string, $( $arg ),*);
}*/
}
};
}
/// function to catch updates
pub fn start_updater_thread(rx: Receiver<StatusMessage>) -> Result<(), Error> {
let _ = thread::Builder::new()
.name("wallet-updater-status".to_string())
.spawn(move || loop {
while let Ok(m) = rx.recv() {
match m {
StatusMessage::UpdatingOutputs(s) => cli_message_inline!("{}", s),
StatusMessage::UpdatingTransactions(s) => cli_message_inline!("{}", s),
StatusMessage::FullScanWarn(s) => cli_message_inline!("{}", s),
StatusMessage::Scanning(_, m) => {
//debug!("{}", s);
cli_message_inline!("Scanning - {}% complete - Please Wait", m);
}
StatusMessage::ScanningComplete(s) => cli_message_inline!("{}", s),
StatusMessage::UpdateWarning(s) => cli_message_inline!("{}", s),
}
}
});
Ok(())
}
pub fn command_loop<L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
keychain_mask: Option<SecretKey>,
wallet_config: &WalletConfig,
tor_config: &TorConfig,
global_wallet_args: &GlobalArgs,
test_mode: bool,
) -> Result<(), Error>
where
DefaultWalletImpl<'static, C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let editor = Config::builder()
.history_ignore_space(true)
.completion_type(CompletionType::List)
.edit_mode(EditMode::Emacs)
.output_stream(OutputStreamType::Stdout)
.build();
let mut reader = Editor::with_config(editor);
reader.set_helper(Some(EditorHelper(
FilenameCompleter::new(),
MatchingBracketHighlighter::new(),
)));
/*let history_file = self
.api
.config()
.get_data_path()
.unwrap()
.parent()
.unwrap()
.join(HISTORY_PATH);
if history_file.exists() {
let _ = reader.load_history(&history_file);
}*/
let yml = load_yaml!("../bin/grin-wallet.yml");
let mut app = App::from_yaml(yml).version(crate_version!());
let mut keychain_mask = keychain_mask;
// catch updater messages
let (tx, rx) = channel();
let mut owner_api = Owner::new(wallet_inst, Some(tx));
start_updater_thread(rx)?;
// start the automatic updater
owner_api.start_updater((&keychain_mask).as_ref(), Duration::from_secs(30))?;
let mut wallet_opened = false;
loop {
match reader.readline(PROMPT) {
Ok(command) => {
if command.is_empty() {
continue;
}
// TODO tidy up a bit
if command.to_lowercase() == "exit" {
break;
}
/* use crate::common::{is_cli, COLORED_PROMPT}; */
// reset buffer
{
let mut contents = STDIN_CONTENTS.lock();
*contents = String::from("");
}
// Just add 'grin-wallet' to each command behind the scenes
// so we don't need to maintain a separate definition file
let augmented_command = format!("grin-wallet {}", command);
let args =
app.get_matches_from_safe_borrow(augmented_command.trim().split_whitespace());
let done = match args {
Ok(args) => {
// handle opening /closing separately
keychain_mask = match args.subcommand() {
("open", Some(_)) => {
let mut wallet_lock = owner_api.wallet_inst.lock();
let lc = wallet_lock.lc_provider().unwrap();
let mask = match lc.open_wallet(
None,
wallet_args::prompt_password(&global_wallet_args.password),
false,
false,
) {
Ok(m) => {
wallet_opened = true;
m
}
Err(e) => {
cli_message!("{}", e);
None
}
};
if let Some(account) = args.value_of("account") {
if wallet_opened {
let wallet_inst = lc.wallet_inst()?;
wallet_inst.set_parent_key_id_by_name(account)?;
}
}
mask
}
("close", Some(_)) => {
let mut wallet_lock = owner_api.wallet_inst.lock();
let lc = wallet_lock.lc_provider().unwrap();
lc.close_wallet(None)?;
None
}
_ => keychain_mask,
};
match wallet_args::parse_and_execute(
&mut owner_api,
keychain_mask.clone(),
&wallet_config,
&tor_config,
&global_wallet_args,
&args,
test_mode,
true,
) {
Ok(_) => {
cli_message!("Command '{}' completed", args.subcommand().0);
false
}
Err(err) => {
cli_message!("{}", err);
false
}
}
}
Err(err) => {
cli_message!("{}", err);
false
}
};
reader.add_history_entry(command);
if done {
println!();
break;
}
}
Err(err) => {
println!("Unable to read line: {}", err);
break;
}
}
}
Ok(())
//let _ = reader.save_history(&history_file);
}
struct EditorHelper(FilenameCompleter, MatchingBracketHighlighter);
impl Completer for EditorHelper {
type Candidate = Pair;
fn complete(
&self,
line: &str,
pos: usize,
ctx: &Context<'_>,
) -> std::result::Result<(usize, Vec<Pair>), ReadlineError> {
self.0.complete(line, pos, ctx)
}
}
impl Hinter for EditorHelper {
fn hint(&self, line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<String> {
let mut contents = STDIN_CONTENTS.lock();
*contents = line.into();
None
}
}
impl Highlighter for EditorHelper {
fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {
self.1.highlight(line, pos)
}
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
default: bool,
) -> Cow<'b, str> {
if default {
Borrowed(COLORED_PROMPT)
} else {
Borrowed(prompt)
}
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned("\x1b[1m".to_owned() + hint + "\x1b[m")
}
fn highlight_char(&self, line: &str, pos: usize) -> bool {
self.1.highlight_char(line, pos)
}
}
impl Validator for EditorHelper {}
impl Helper for EditorHelper {}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2020 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 cli;
pub use cli::command_loop;
+91 -37
View File
@@ -13,12 +13,15 @@
// limitations under the License.
use crate::api::TLSConfig;
use crate::cli::command_loop;
use crate::config::GRIN_WALLET_DIR;
use crate::util::file::get_first_line;
use crate::util::secp::key::SecretKey;
use crate::util::{Mutex, ZeroingString};
/// Argument parsing and error handling for wallet commands
use clap::ArgMatches;
use failure::Fail;
use grin_wallet_api::Owner;
use grin_wallet_config::{config_file_exists, TorConfig, WalletConfig};
use grin_wallet_controller::command;
use grin_wallet_controller::{Error, ErrorKind};
@@ -922,6 +925,7 @@ where
match wallet_args.subcommand() {
("init", Some(_)) => open_wallet = false,
("recover", _) => open_wallet = false,
("cli", _) => open_wallet = false,
("owner_api", _) => {
// If wallet exists, open it. Otherwise, that's fine too.
let mut wallet_lock = wallet.lock();
@@ -950,34 +954,81 @@ where
false => None,
};
let km = (&keychain_mask).as_ref();
let res = match wallet_args.subcommand() {
("cli", Some(_)) => command_loop(
wallet,
keychain_mask,
&wallet_config,
&tor_config,
&global_wallet_args,
test_mode,
),
_ => {
let mut owner_api = Owner::new(wallet, None);
parse_and_execute(
&mut owner_api,
keychain_mask,
&wallet_config,
&tor_config,
&global_wallet_args,
&wallet_args,
test_mode,
false,
)
}
};
if let Err(e) = res {
Err(e)
} else {
Ok(wallet_args.subcommand().0.to_owned())
}
}
pub fn parse_and_execute<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<SecretKey>,
wallet_config: &WalletConfig,
tor_config: &TorConfig,
global_wallet_args: &command::GlobalArgs,
wallet_args: &ArgMatches,
test_mode: bool,
cli_mode: bool,
) -> Result<(), Error>
where
DefaultWalletImpl<'static, C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let km = (&keychain_mask).as_ref();
match wallet_args.subcommand() {
("init", Some(args)) => {
let a = arg_parse!(parse_init_args(
wallet.clone(),
&wallet_config,
&global_wallet_args,
owner_api.wallet_inst.clone(),
wallet_config,
global_wallet_args,
&args,
test_mode,
));
command::init(wallet, &global_wallet_args, a)
command::init(owner_api, &global_wallet_args, a)
}
("recover", Some(_)) => {
let a = arg_parse!(parse_recover_args(&global_wallet_args,));
command::recover(wallet, a)
command::recover(owner_api, a)
}
("listen", Some(args)) => {
let mut c = wallet_config.clone();
let mut t = tor_config.clone();
let a = arg_parse!(parse_listen_args(&mut c, &mut t, &args));
command::listen(
wallet,
owner_api,
Arc::new(Mutex::new(keychain_mask)),
&c,
&t,
&a,
&global_wallet_args.clone(),
cli_mode,
)
}
("owner_api", Some(args)) => {
@@ -985,47 +1036,47 @@ where
let mut g = global_wallet_args.clone();
g.tls_conf = None;
arg_parse!(parse_owner_api_args(&mut c, &args));
command::owner_api(wallet, keychain_mask, &c, &tor_config, &g)
command::owner_api(owner_api, keychain_mask, &c, &tor_config, &g)
}
("web", Some(_)) => command::owner_api(
wallet,
owner_api,
keychain_mask,
&wallet_config,
&tor_config,
&global_wallet_args,
wallet_config,
tor_config,
global_wallet_args,
),
("account", Some(args)) => {
let a = arg_parse!(parse_account_args(&args));
command::account(wallet, km, a)
command::account(owner_api, km, a)
}
("send", Some(args)) => {
let a = arg_parse!(parse_send_args(&args));
command::send(
wallet,
owner_api,
km,
Some(tor_config),
Some(tor_config.clone()),
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
}
("receive", Some(args)) => {
let a = arg_parse!(parse_receive_args(&args));
command::receive(wallet, km, &global_wallet_args, a)
command::receive(owner_api, km, &global_wallet_args, a)
}
("finalize", Some(args)) => {
let a = arg_parse!(parse_finalize_args(&args));
command::finalize(wallet, km, a)
command::finalize(owner_api, km, a)
}
("invoice", Some(args)) => {
let a = arg_parse!(parse_issue_invoice_args(&args));
command::issue_invoice_tx(wallet, km, a)
command::issue_invoice_tx(owner_api, km, a)
}
("pay", Some(args)) => {
let a = arg_parse!(parse_process_invoice_args(&args, !test_mode));
command::process_invoice(
wallet,
owner_api,
km,
Some(tor_config),
Some(tor_config.clone()),
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
@@ -1033,15 +1084,15 @@ where
("info", Some(args)) => {
let a = arg_parse!(parse_info_args(&args));
command::info(
wallet,
owner_api,
km,
&global_wallet_args,
global_wallet_args,
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
}
("outputs", Some(_)) => command::outputs(
wallet,
owner_api,
km,
&global_wallet_args,
wallet_config.dark_background_color_scheme.unwrap_or(true),
@@ -1049,7 +1100,7 @@ where
("txs", Some(args)) => {
let a = arg_parse!(parse_txs_args(&args));
command::txs(
wallet,
owner_api,
km,
&global_wallet_args,
a,
@@ -1058,37 +1109,40 @@ where
}
("post", Some(args)) => {
let a = arg_parse!(parse_post_args(&args));
command::post(wallet, km, a)
command::post(owner_api, km, a)
}
("repost", Some(args)) => {
let a = arg_parse!(parse_repost_args(&args));
command::repost(wallet, km, a)
command::repost(owner_api, km, a)
}
("cancel", Some(args)) => {
let a = arg_parse!(parse_cancel_args(&args));
command::cancel(wallet, km, a)
command::cancel(owner_api, km, a)
}
("export_proof", Some(args)) => {
let a = arg_parse!(parse_export_proof_args(&args));
command::proof_export(wallet, km, a)
command::proof_export(owner_api, km, a)
}
("verify_proof", Some(args)) => {
let a = arg_parse!(parse_verify_proof_args(&args));
command::proof_verify(wallet, km, a)
command::proof_verify(owner_api, km, a)
}
("address", Some(_)) => command::address(wallet, &global_wallet_args, km),
("address", Some(_)) => command::address(owner_api, &global_wallet_args, km),
("scan", Some(args)) => {
let a = arg_parse!(parse_check_args(&args));
command::scan(wallet, km, a)
command::scan(owner_api, km, a)
}
("open", Some(_)) => {
// for CLI mode only, should be handled externally
Ok(())
}
("close", Some(_)) => {
// for CLI mode only, should be handled externally
Ok(())
}
_ => {
let msg = format!("Unknown wallet command, use 'grin-wallet help' for details");
return Err(ErrorKind::ArgumentError(msg).into());
}
};
if let Err(e) = res {
Err(e)
} else {
Ok(wallet_args.subcommand().0.to_owned())
}
}
+6
View File
@@ -11,8 +11,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate clap;
use grin_wallet_config as config;
use grin_wallet_util::grin_api as api;
use grin_wallet_util::grin_util as util;
mod cli;
pub mod cmd;