mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-12-02 20:04:40 +01:00
initial commit
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,90 @@
|
||||
// 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.
|
||||
|
||||
/// Grin configuration file output command
|
||||
use crate::config::{config, GlobalConfig, GlobalWalletConfig, GRIN_WALLET_DIR};
|
||||
use crate::core::global;
|
||||
use std::env;
|
||||
|
||||
/// Create a config file in the current directory
|
||||
pub fn config_command_server(chain_type: &global::ChainTypes, file_name: &str) {
|
||||
let mut default_config = GlobalConfig::for_chain(chain_type);
|
||||
let current_dir = env::current_dir().unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
let mut config_file_name = current_dir.clone();
|
||||
config_file_name.push(file_name);
|
||||
if config_file_name.exists() {
|
||||
panic!(
|
||||
"{} already exists in the current directory. Please remove it first",
|
||||
file_name
|
||||
);
|
||||
}
|
||||
default_config.update_paths(¤t_dir);
|
||||
default_config
|
||||
.write_to_file(config_file_name.to_str().unwrap())
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
|
||||
println!(
|
||||
"{} file configured and created in current directory",
|
||||
file_name
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a config file in the current directory
|
||||
pub fn config_command_wallet(chain_type: &global::ChainTypes, file_name: &str) {
|
||||
let mut default_config = GlobalWalletConfig::for_chain(chain_type);
|
||||
let current_dir = env::current_dir().unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
let mut config_file_name = current_dir.clone();
|
||||
config_file_name.push(file_name);
|
||||
|
||||
let mut data_dir_name = current_dir.clone();
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
|
||||
if config_file_name.exists() && data_dir_name.exists() {
|
||||
panic!(
|
||||
"{} already exists in the target directory. Please remove it first",
|
||||
file_name
|
||||
);
|
||||
}
|
||||
|
||||
// just leave as is if file exists but there's no data dir
|
||||
if config_file_name.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
default_config.update_paths(¤t_dir);
|
||||
default_config
|
||||
.write_to_file(config_file_name.to_str().unwrap())
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
|
||||
println!(
|
||||
"File {} configured and created",
|
||||
config_file_name.to_str().unwrap(),
|
||||
);
|
||||
|
||||
let mut api_secret_path = current_dir.clone();
|
||||
api_secret_path.push(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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// 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.
|
||||
|
||||
mod config;
|
||||
mod wallet;
|
||||
mod wallet_args;
|
||||
mod wallet_tests;
|
||||
|
||||
pub use self::config::{config_command_server, config_command_wallet};
|
||||
pub use self::wallet::{seed_exists, wallet_command};
|
||||
@@ -0,0 +1,68 @@
|
||||
// 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 crate::cmd::wallet_args;
|
||||
use crate::config::GlobalWalletConfig;
|
||||
use clap::ArgMatches;
|
||||
use grin_wallet::{self, HTTPNodeClient, WalletConfig, WalletSeed};
|
||||
use std::path::PathBuf;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn _init_wallet_seed(wallet_config: WalletConfig, password: &str) {
|
||||
if let Err(_) = WalletSeed::from_file(&wallet_config, password) {
|
||||
WalletSeed::init_file(&wallet_config, 32, None, password)
|
||||
.expect("Failed to create wallet seed file.");
|
||||
};
|
||||
}
|
||||
|
||||
pub fn seed_exists(wallet_config: WalletConfig) -> bool {
|
||||
let mut data_file_dir = PathBuf::new();
|
||||
data_file_dir.push(wallet_config.data_file_dir);
|
||||
data_file_dir.push(grin_wallet::SEED_FILE);
|
||||
if data_file_dir.exists() {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wallet_command(wallet_args: &ArgMatches<'_>, config: GlobalWalletConfig) -> i32 {
|
||||
// just get defaults from the global config
|
||||
let wallet_config = config.members.unwrap().wallet;
|
||||
|
||||
// web wallet http server must be started from here
|
||||
// NB: Turned off for the time being
|
||||
/*let _ = match wallet_args.subcommand() {
|
||||
("web", Some(_)) => start_webwallet_server(),
|
||||
_ => {}
|
||||
};*/
|
||||
|
||||
let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None);
|
||||
let res = wallet_args::wallet_command(wallet_args, wallet_config, node_client);
|
||||
|
||||
// we need to give log output a chance to catch up before exiting
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
|
||||
if let Err(e) = res {
|
||||
println!("Wallet command failed: {}", e);
|
||||
1
|
||||
} else {
|
||||
println!(
|
||||
"Command '{}' completed successfully",
|
||||
wallet_args.subcommand().0
|
||||
);
|
||||
0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
// 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 crate::api::TLSConfig;
|
||||
use crate::util::file::get_first_line;
|
||||
use crate::util::{Mutex, ZeroingString};
|
||||
/// Argument parsing and error handling for wallet commands
|
||||
use clap::ArgMatches;
|
||||
use failure::Fail;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_wallet::{command, instantiate_wallet, NodeClient, WalletConfig, WalletInst, WalletSeed};
|
||||
use grin_wallet::{Error, ErrorKind};
|
||||
use linefeed::terminal::Signal;
|
||||
use linefeed::{Interface, ReadResult};
|
||||
use rpassword;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
// define what to do on argument error
|
||||
macro_rules! arg_parse {
|
||||
( $r:expr ) => {
|
||||
match $r {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
return Err(ErrorKind::ArgumentError(format!("{}", e)).into());
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
/// Simple error definition, just so we can return errors from all commands
|
||||
/// and let the caller figure out what to do
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
|
||||
pub enum ParseError {
|
||||
#[fail(display = "Invalid Arguments: {}", _0)]
|
||||
ArgumentError(String),
|
||||
#[fail(display = "Parsing IO error: {}", _0)]
|
||||
IOError(String),
|
||||
#[fail(display = "User Cancelled")]
|
||||
CancelledError,
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for ParseError {
|
||||
fn from(e: std::io::Error) -> ParseError {
|
||||
ParseError::IOError(format!("{}", e))
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_password_stdout(prompt: &str) -> ZeroingString {
|
||||
ZeroingString::from(rpassword::prompt_password_stdout(prompt).unwrap())
|
||||
}
|
||||
|
||||
pub fn prompt_password(password: &Option<ZeroingString>) -> ZeroingString {
|
||||
match password {
|
||||
None => prompt_password_stdout("Password: "),
|
||||
Some(p) => p.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_password_confirm() -> ZeroingString {
|
||||
let mut first = ZeroingString::from("first");
|
||||
let mut second = ZeroingString::from("second");
|
||||
while first != second {
|
||||
first = prompt_password_stdout("Password: ");
|
||||
second = prompt_password_stdout("Confirm Password: ");
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
fn prompt_replace_seed() -> Result<bool, ParseError> {
|
||||
let interface = Arc::new(Interface::new("replace_seed")?);
|
||||
interface.set_report_signal(Signal::Interrupt, true);
|
||||
interface.set_prompt("Replace seed? (y/n)> ")?;
|
||||
println!();
|
||||
println!("Existing wallet.seed file already exists. Continue?");
|
||||
println!("Continuing will back up your existing 'wallet.seed' file as 'wallet.seed.bak'");
|
||||
println!();
|
||||
loop {
|
||||
let res = interface.read_line()?;
|
||||
match res {
|
||||
ReadResult::Eof => return Ok(false),
|
||||
ReadResult::Signal(sig) => {
|
||||
if sig == Signal::Interrupt {
|
||||
interface.cancel_read_line()?;
|
||||
return Err(ParseError::CancelledError);
|
||||
}
|
||||
}
|
||||
ReadResult::Input(line) => match line.trim() {
|
||||
"Y" | "y" => return Ok(true),
|
||||
"N" | "n" => return Ok(false),
|
||||
_ => println!("Please respond y or n"),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_recovery_phrase() -> Result<ZeroingString, ParseError> {
|
||||
let interface = Arc::new(Interface::new("recover")?);
|
||||
let mut phrase = ZeroingString::from("");
|
||||
interface.set_report_signal(Signal::Interrupt, true);
|
||||
interface.set_prompt("phrase> ")?;
|
||||
loop {
|
||||
println!("Please enter your recovery phrase:");
|
||||
let res = interface.read_line()?;
|
||||
match res {
|
||||
ReadResult::Eof => break,
|
||||
ReadResult::Signal(sig) => {
|
||||
if sig == Signal::Interrupt {
|
||||
interface.cancel_read_line()?;
|
||||
return Err(ParseError::CancelledError);
|
||||
}
|
||||
}
|
||||
ReadResult::Input(line) => {
|
||||
if WalletSeed::from_mnemonic(&line).is_ok() {
|
||||
phrase = ZeroingString::from(line);
|
||||
break;
|
||||
} else {
|
||||
println!();
|
||||
println!("Recovery word phrase is invalid.");
|
||||
println!();
|
||||
interface.set_buffer(&line)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(phrase)
|
||||
}
|
||||
|
||||
// instantiate wallet (needed by most functions)
|
||||
|
||||
pub fn inst_wallet(
|
||||
config: WalletConfig,
|
||||
g_args: &command::GlobalArgs,
|
||||
node_client: impl NodeClient + 'static,
|
||||
) -> Result<Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>, ParseError> {
|
||||
let passphrase = prompt_password(&g_args.password);
|
||||
let res = instantiate_wallet(config.clone(), node_client, &passphrase, &g_args.account);
|
||||
match res {
|
||||
Ok(p) => Ok(p),
|
||||
Err(e) => {
|
||||
let msg = {
|
||||
match e.kind() {
|
||||
ErrorKind::Encryption => {
|
||||
format!("Error decrypting wallet seed (check provided password)")
|
||||
}
|
||||
_ => format!("Error instantiating wallet: {}", e),
|
||||
}
|
||||
};
|
||||
Err(ParseError::ArgumentError(msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parses a required value, or throws error with message otherwise
|
||||
fn parse_required<'a>(args: &'a ArgMatches, name: &str) -> Result<&'a str, ParseError> {
|
||||
let arg = args.value_of(name);
|
||||
match arg {
|
||||
Some(ar) => Ok(ar),
|
||||
None => {
|
||||
let msg = format!("Value for argument '{}' is required in this context", name,);
|
||||
Err(ParseError::ArgumentError(msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parses a number, or throws error with message otherwise
|
||||
fn parse_u64(arg: &str, name: &str) -> Result<u64, ParseError> {
|
||||
let val = arg.parse::<u64>();
|
||||
match val {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => {
|
||||
let msg = format!("Could not parse {} as a whole number. e={}", name, e);
|
||||
Err(ParseError::ArgumentError(msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_global_args(
|
||||
config: &WalletConfig,
|
||||
args: &ArgMatches,
|
||||
) -> Result<command::GlobalArgs, ParseError> {
|
||||
let account = parse_required(args, "account")?;
|
||||
let mut show_spent = false;
|
||||
if args.is_present("show_spent") {
|
||||
show_spent = true;
|
||||
}
|
||||
let node_api_secret = get_first_line(config.node_api_secret_path.clone());
|
||||
let password = match args.value_of("pass") {
|
||||
None => None,
|
||||
Some(p) => Some(ZeroingString::from(p)),
|
||||
};
|
||||
|
||||
let tls_conf = match config.tls_certificate_file.clone() {
|
||||
None => None,
|
||||
Some(file) => {
|
||||
let key = match config.tls_certificate_key.clone() {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
let msg = format!("Private key for certificate is not set");
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
};
|
||||
Some(TLSConfig::new(file, key))
|
||||
}
|
||||
};
|
||||
|
||||
Ok(command::GlobalArgs {
|
||||
account: account.to_owned(),
|
||||
show_spent: show_spent,
|
||||
node_api_secret: node_api_secret,
|
||||
password: password,
|
||||
tls_conf: tls_conf,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_init_args(
|
||||
config: &WalletConfig,
|
||||
g_args: &command::GlobalArgs,
|
||||
args: &ArgMatches,
|
||||
) -> Result<command::InitArgs, ParseError> {
|
||||
if let Err(e) = WalletSeed::seed_file_exists(config) {
|
||||
let msg = format!("Not creating wallet - {}", e.inner);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
let list_length = match args.is_present("short_wordlist") {
|
||||
false => 32,
|
||||
true => 16,
|
||||
};
|
||||
let recovery_phrase = match args.is_present("recover") {
|
||||
true => Some(prompt_recovery_phrase()?),
|
||||
false => None,
|
||||
};
|
||||
|
||||
if recovery_phrase.is_some() {
|
||||
println!("Please provide a new password for the recovered wallet");
|
||||
} else {
|
||||
println!("Please enter a password for your new wallet");
|
||||
}
|
||||
|
||||
let password = match g_args.password.clone() {
|
||||
Some(p) => p,
|
||||
None => prompt_password_confirm(),
|
||||
};
|
||||
|
||||
Ok(command::InitArgs {
|
||||
list_length: list_length,
|
||||
password: password,
|
||||
config: config.clone(),
|
||||
recovery_phrase: recovery_phrase,
|
||||
restore: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_recover_args(
|
||||
config: &WalletConfig,
|
||||
g_args: &command::GlobalArgs,
|
||||
args: &ArgMatches,
|
||||
) -> Result<command::RecoverArgs, ParseError> {
|
||||
let (passphrase, recovery_phrase) = {
|
||||
match args.is_present("display") {
|
||||
true => (prompt_password(&g_args.password), None),
|
||||
false => {
|
||||
let cont = {
|
||||
if command::wallet_seed_exists(config).is_err() {
|
||||
prompt_replace_seed()?
|
||||
} else {
|
||||
true
|
||||
}
|
||||
};
|
||||
if !cont {
|
||||
return Err(ParseError::CancelledError);
|
||||
}
|
||||
let phrase = prompt_recovery_phrase()?;
|
||||
println!("Please provide a new password for the recovered wallet");
|
||||
(prompt_password_confirm(), Some(phrase.to_owned()))
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(command::RecoverArgs {
|
||||
passphrase: passphrase,
|
||||
recovery_phrase: recovery_phrase,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_listen_args(
|
||||
config: &mut WalletConfig,
|
||||
g_args: &mut command::GlobalArgs,
|
||||
args: &ArgMatches,
|
||||
) -> Result<command::ListenArgs, ParseError> {
|
||||
// listen args
|
||||
let pass = match g_args.password.clone() {
|
||||
Some(p) => Some(p.to_owned()),
|
||||
None => Some(prompt_password(&None)),
|
||||
};
|
||||
g_args.password = pass;
|
||||
if let Some(port) = args.value_of("port") {
|
||||
config.api_listen_port = port.parse().unwrap();
|
||||
}
|
||||
let method = parse_required(args, "method")?;
|
||||
Ok(command::ListenArgs {
|
||||
method: method.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_account_args(account_args: &ArgMatches) -> Result<command::AccountArgs, ParseError> {
|
||||
let create = match account_args.value_of("create") {
|
||||
None => None,
|
||||
Some(s) => Some(s.to_owned()),
|
||||
};
|
||||
Ok(command::AccountArgs { create: create })
|
||||
}
|
||||
|
||||
pub fn parse_send_args(args: &ArgMatches) -> Result<command::SendArgs, ParseError> {
|
||||
// amount
|
||||
let amount = parse_required(args, "amount")?;
|
||||
let amount = core::core::amount_from_hr_string(amount);
|
||||
let amount = match amount {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
let msg = format!(
|
||||
"Could not parse amount as a number with optional decimal point. e={}",
|
||||
e
|
||||
);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
};
|
||||
|
||||
// message
|
||||
let message = match args.is_present("message") {
|
||||
true => Some(args.value_of("message").unwrap().to_owned()),
|
||||
false => None,
|
||||
};
|
||||
|
||||
// minimum_confirmations
|
||||
let min_c = parse_required(args, "minimum_confirmations")?;
|
||||
let min_c = parse_u64(min_c, "minimum_confirmations")?;
|
||||
|
||||
// selection_strategy
|
||||
let selection_strategy = parse_required(args, "selection_strategy")?;
|
||||
|
||||
// estimate_selection_strategies
|
||||
let estimate_selection_strategies = args.is_present("estimate_selection_strategies");
|
||||
|
||||
// method
|
||||
let method = parse_required(args, "method")?;
|
||||
|
||||
// dest
|
||||
let dest = {
|
||||
if method == "self" {
|
||||
match args.value_of("dest") {
|
||||
Some(d) => d,
|
||||
None => "default",
|
||||
}
|
||||
} else {
|
||||
if !estimate_selection_strategies {
|
||||
parse_required(args, "dest")?
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
};
|
||||
if !estimate_selection_strategies
|
||||
&& method == "http"
|
||||
&& !dest.starts_with("http://")
|
||||
&& !dest.starts_with("https://")
|
||||
{
|
||||
let msg = format!(
|
||||
"HTTP Destination should start with http://: or https://: {}",
|
||||
dest,
|
||||
);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
|
||||
// change_outputs
|
||||
let change_outputs = parse_required(args, "change_outputs")?;
|
||||
let change_outputs = parse_u64(change_outputs, "change_outputs")? as usize;
|
||||
|
||||
// fluff
|
||||
let fluff = args.is_present("fluff");
|
||||
|
||||
// max_outputs
|
||||
let max_outputs = 500;
|
||||
|
||||
Ok(command::SendArgs {
|
||||
amount: amount,
|
||||
message: message,
|
||||
minimum_confirmations: min_c,
|
||||
selection_strategy: selection_strategy.to_owned(),
|
||||
estimate_selection_strategies,
|
||||
method: method.to_owned(),
|
||||
dest: dest.to_owned(),
|
||||
change_outputs: change_outputs,
|
||||
fluff: fluff,
|
||||
max_outputs: max_outputs,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_receive_args(receive_args: &ArgMatches) -> Result<command::ReceiveArgs, ParseError> {
|
||||
// message
|
||||
let message = match receive_args.is_present("message") {
|
||||
true => Some(receive_args.value_of("message").unwrap().to_owned()),
|
||||
false => None,
|
||||
};
|
||||
|
||||
// input
|
||||
let tx_file = parse_required(receive_args, "input")?;
|
||||
|
||||
// validate input
|
||||
if !Path::new(&tx_file).is_file() {
|
||||
let msg = format!("File {} not found.", &tx_file);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
|
||||
Ok(command::ReceiveArgs {
|
||||
input: tx_file.to_owned(),
|
||||
message: message,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_finalize_args(args: &ArgMatches) -> Result<command::FinalizeArgs, ParseError> {
|
||||
let fluff = args.is_present("fluff");
|
||||
let tx_file = parse_required(args, "input")?;
|
||||
|
||||
if !Path::new(&tx_file).is_file() {
|
||||
let msg = format!("File {} not found.", tx_file);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
Ok(command::FinalizeArgs {
|
||||
input: tx_file.to_owned(),
|
||||
fluff: fluff,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_info_args(args: &ArgMatches) -> Result<command::InfoArgs, ParseError> {
|
||||
// minimum_confirmations
|
||||
let mc = parse_required(args, "minimum_confirmations")?;
|
||||
let mc = parse_u64(mc, "minimum_confirmations")?;
|
||||
Ok(command::InfoArgs {
|
||||
minimum_confirmations: mc,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_txs_args(args: &ArgMatches) -> Result<command::TxsArgs, ParseError> {
|
||||
let tx_id = match args.value_of("id") {
|
||||
None => None,
|
||||
Some(tx) => Some(parse_u64(tx, "id")? as u32),
|
||||
};
|
||||
Ok(command::TxsArgs { id: tx_id })
|
||||
}
|
||||
|
||||
pub fn parse_repost_args(args: &ArgMatches) -> Result<command::RepostArgs, ParseError> {
|
||||
let tx_id = match args.value_of("id") {
|
||||
None => None,
|
||||
Some(tx) => Some(parse_u64(tx, "id")? as u32),
|
||||
};
|
||||
|
||||
let fluff = args.is_present("fluff");
|
||||
let dump_file = match args.value_of("dumpfile") {
|
||||
None => None,
|
||||
Some(d) => Some(d.to_owned()),
|
||||
};
|
||||
|
||||
Ok(command::RepostArgs {
|
||||
id: tx_id.unwrap(),
|
||||
dump_file: dump_file,
|
||||
fluff: fluff,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_cancel_args(args: &ArgMatches) -> Result<command::CancelArgs, ParseError> {
|
||||
let mut tx_id_string = "";
|
||||
let tx_id = match args.value_of("id") {
|
||||
None => None,
|
||||
Some(tx) => Some(parse_u64(tx, "id")? as u32),
|
||||
};
|
||||
let tx_slate_id = match args.value_of("txid") {
|
||||
None => None,
|
||||
Some(tx) => match tx.parse() {
|
||||
Ok(t) => {
|
||||
tx_id_string = tx;
|
||||
Some(t)
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = format!("Could not parse txid parameter. e={}", e);
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
},
|
||||
};
|
||||
if (tx_id.is_none() && tx_slate_id.is_none()) || (tx_id.is_some() && tx_slate_id.is_some()) {
|
||||
let msg = format!("'id' (-i) or 'txid' (-t) argument is required.");
|
||||
return Err(ParseError::ArgumentError(msg));
|
||||
}
|
||||
Ok(command::CancelArgs {
|
||||
tx_id: tx_id,
|
||||
tx_slate_id: tx_slate_id,
|
||||
tx_id_string: tx_id_string.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn wallet_command(
|
||||
wallet_args: &ArgMatches,
|
||||
mut wallet_config: WalletConfig,
|
||||
mut node_client: impl NodeClient + 'static,
|
||||
) -> Result<String, Error> {
|
||||
if let Some(t) = wallet_config.chain_type.clone() {
|
||||
core::global::set_mining_mode(t);
|
||||
}
|
||||
|
||||
if wallet_args.is_present("external") {
|
||||
wallet_config.api_listen_interface = "0.0.0.0".to_string();
|
||||
}
|
||||
|
||||
if let Some(dir) = wallet_args.value_of("data_dir") {
|
||||
wallet_config.data_file_dir = dir.to_string().clone();
|
||||
}
|
||||
|
||||
if let Some(sa) = wallet_args.value_of("api_server_address") {
|
||||
wallet_config.check_node_api_http_addr = sa.to_string().clone();
|
||||
}
|
||||
|
||||
let global_wallet_args = arg_parse!(parse_global_args(&wallet_config, &wallet_args));
|
||||
|
||||
node_client.set_node_url(&wallet_config.check_node_api_http_addr);
|
||||
node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone());
|
||||
|
||||
// closure to instantiate wallet as needed by each subcommand
|
||||
let inst_wallet = || {
|
||||
let res = inst_wallet(wallet_config.clone(), &global_wallet_args, node_client);
|
||||
res.unwrap_or_else(|e| {
|
||||
println!("{}", e);
|
||||
std::process::exit(1);
|
||||
})
|
||||
};
|
||||
|
||||
let res = match wallet_args.subcommand() {
|
||||
("init", Some(args)) => {
|
||||
let a = arg_parse!(parse_init_args(&wallet_config, &global_wallet_args, &args));
|
||||
command::init(&global_wallet_args, a)
|
||||
}
|
||||
("recover", Some(args)) => {
|
||||
let a = arg_parse!(parse_recover_args(
|
||||
&wallet_config,
|
||||
&global_wallet_args,
|
||||
&args
|
||||
));
|
||||
command::recover(&wallet_config, a)
|
||||
}
|
||||
("listen", Some(args)) => {
|
||||
let mut c = wallet_config.clone();
|
||||
let mut g = global_wallet_args.clone();
|
||||
let a = arg_parse!(parse_listen_args(&mut c, &mut g, &args));
|
||||
command::listen(&wallet_config, &a, &g)
|
||||
}
|
||||
("owner_api", Some(_)) => {
|
||||
let mut g = global_wallet_args.clone();
|
||||
g.tls_conf = None;
|
||||
command::owner_api(inst_wallet(), &wallet_config, &g)
|
||||
}
|
||||
("web", Some(_)) => command::owner_api(inst_wallet(), &wallet_config, &global_wallet_args),
|
||||
("account", Some(args)) => {
|
||||
let a = arg_parse!(parse_account_args(&args));
|
||||
command::account(inst_wallet(), a)
|
||||
}
|
||||
("send", Some(args)) => {
|
||||
let a = arg_parse!(parse_send_args(&args));
|
||||
command::send(
|
||||
inst_wallet(),
|
||||
a,
|
||||
wallet_config.dark_background_color_scheme.unwrap_or(true),
|
||||
)
|
||||
}
|
||||
("receive", Some(args)) => {
|
||||
let a = arg_parse!(parse_receive_args(&args));
|
||||
command::receive(inst_wallet(), &global_wallet_args, a)
|
||||
}
|
||||
("finalize", Some(args)) => {
|
||||
let a = arg_parse!(parse_finalize_args(&args));
|
||||
command::finalize(inst_wallet(), a)
|
||||
}
|
||||
("info", Some(args)) => {
|
||||
let a = arg_parse!(parse_info_args(&args));
|
||||
command::info(
|
||||
inst_wallet(),
|
||||
&global_wallet_args,
|
||||
a,
|
||||
wallet_config.dark_background_color_scheme.unwrap_or(true),
|
||||
)
|
||||
}
|
||||
("outputs", Some(_)) => command::outputs(
|
||||
inst_wallet(),
|
||||
&global_wallet_args,
|
||||
wallet_config.dark_background_color_scheme.unwrap_or(true),
|
||||
),
|
||||
("txs", Some(args)) => {
|
||||
let a = arg_parse!(parse_txs_args(&args));
|
||||
command::txs(
|
||||
inst_wallet(),
|
||||
&global_wallet_args,
|
||||
a,
|
||||
wallet_config.dark_background_color_scheme.unwrap_or(true),
|
||||
)
|
||||
}
|
||||
("repost", Some(args)) => {
|
||||
let a = arg_parse!(parse_repost_args(&args));
|
||||
command::repost(inst_wallet(), a)
|
||||
}
|
||||
("cancel", Some(args)) => {
|
||||
let a = arg_parse!(parse_cancel_args(&args));
|
||||
command::cancel(inst_wallet(), a)
|
||||
}
|
||||
("restore", Some(_)) => command::restore(inst_wallet()),
|
||||
("check", Some(_)) => command::check_repair(inst_wallet()),
|
||||
_ => {
|
||||
let msg = format!("Unknown wallet command, use 'grin help wallet' for details");
|
||||
return Err(ErrorKind::ArgumentError(msg).into());
|
||||
}
|
||||
};
|
||||
if let Err(e) = res {
|
||||
Err(e)
|
||||
} else {
|
||||
Ok(wallet_args.subcommand().0.to_owned())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
// 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.
|
||||
|
||||
//! Test wallet command line works as expected
|
||||
#[cfg(test)]
|
||||
mod wallet_tests {
|
||||
use clap;
|
||||
use grin_util as util;
|
||||
use grin_wallet;
|
||||
|
||||
use grin_wallet::test_framework::{self, LocalWalletClient, WalletProxy};
|
||||
|
||||
use clap::{App, ArgMatches};
|
||||
use grin_util::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::{env, fs};
|
||||
|
||||
use grin_config::GlobalWalletConfig;
|
||||
use grin_core::global;
|
||||
use grin_core::global::ChainTypes;
|
||||
use grin_keychain::ExtKeychain;
|
||||
use grin_wallet::{LMDBBackend, WalletBackend, WalletConfig, WalletInst, WalletSeed};
|
||||
|
||||
use super::super::wallet_args;
|
||||
|
||||
fn clean_output_dir(test_dir: &str) {
|
||||
let _ = fs::remove_dir_all(test_dir);
|
||||
}
|
||||
|
||||
fn setup(test_dir: &str) {
|
||||
util::init_test_logger();
|
||||
clean_output_dir(test_dir);
|
||||
global::set_mining_mode(ChainTypes::AutomatedTesting);
|
||||
}
|
||||
|
||||
/// Create a wallet config file in the given current directory
|
||||
pub fn config_command_wallet(
|
||||
dir_name: &str,
|
||||
wallet_name: &str,
|
||||
) -> Result<(), grin_wallet::Error> {
|
||||
let mut current_dir;
|
||||
let mut default_config = GlobalWalletConfig::default();
|
||||
current_dir = env::current_dir().unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
current_dir.push(dir_name);
|
||||
current_dir.push(wallet_name);
|
||||
let _ = fs::create_dir_all(current_dir.clone());
|
||||
let mut config_file_name = current_dir.clone();
|
||||
config_file_name.push("grin-wallet.toml");
|
||||
if config_file_name.exists() {
|
||||
return Err(grin_wallet::ErrorKind::ArgumentError(
|
||||
"grin-wallet.toml already exists in the target directory. Please remove it first"
|
||||
.to_owned(),
|
||||
))?;
|
||||
}
|
||||
default_config.update_paths(¤t_dir);
|
||||
default_config
|
||||
.write_to_file(config_file_name.to_str().unwrap())
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
|
||||
println!(
|
||||
"File {} configured and created",
|
||||
config_file_name.to_str().unwrap(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handles setup and detection of paths for wallet
|
||||
pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> WalletConfig {
|
||||
let mut current_dir;
|
||||
current_dir = env::current_dir().unwrap_or_else(|e| {
|
||||
panic!("Error creating config file: {}", e);
|
||||
});
|
||||
current_dir.push(dir_name);
|
||||
current_dir.push(wallet_name);
|
||||
let _ = fs::create_dir_all(current_dir.clone());
|
||||
let mut config_file_name = current_dir.clone();
|
||||
config_file_name.push("grin-wallet.toml");
|
||||
GlobalWalletConfig::new(config_file_name.to_str().unwrap())
|
||||
.unwrap()
|
||||
.members
|
||||
.unwrap()
|
||||
.wallet
|
||||
}
|
||||
|
||||
fn get_wallet_subcommand<'a>(
|
||||
wallet_dir: &str,
|
||||
wallet_name: &str,
|
||||
args: ArgMatches<'a>,
|
||||
) -> ArgMatches<'a> {
|
||||
match args.subcommand() {
|
||||
("wallet", Some(wallet_args)) => {
|
||||
// wallet init command should spit out its config file then continue
|
||||
// (if desired)
|
||||
if let ("init", Some(init_args)) = wallet_args.subcommand() {
|
||||
if init_args.is_present("here") {
|
||||
let _ = config_command_wallet(wallet_dir, wallet_name);
|
||||
}
|
||||
}
|
||||
wallet_args.to_owned()
|
||||
}
|
||||
_ => ArgMatches::new(),
|
||||
}
|
||||
}
|
||||
//
|
||||
// Helper to create an instance of the LMDB wallet
|
||||
fn instantiate_wallet(
|
||||
mut wallet_config: WalletConfig,
|
||||
node_client: LocalWalletClient,
|
||||
passphrase: &str,
|
||||
account: &str,
|
||||
) -> Result<Arc<Mutex<WalletInst<LocalWalletClient, ExtKeychain>>>, grin_wallet::Error> {
|
||||
wallet_config.chain_type = None;
|
||||
// First test decryption, so we can abort early if we have the wrong password
|
||||
let _ = WalletSeed::from_file(&wallet_config, passphrase)?;
|
||||
let mut db_wallet = LMDBBackend::new(wallet_config.clone(), passphrase, node_client)?;
|
||||
db_wallet.set_parent_key_id_by_name(account)?;
|
||||
info!("Using LMDB Backend for wallet");
|
||||
Ok(Arc::new(Mutex::new(db_wallet)))
|
||||
}
|
||||
|
||||
fn execute_command(
|
||||
app: &App,
|
||||
test_dir: &str,
|
||||
wallet_name: &str,
|
||||
client: &LocalWalletClient,
|
||||
arg_vec: Vec<&str>,
|
||||
) -> Result<String, grin_wallet::Error> {
|
||||
let args = app.clone().get_matches_from(arg_vec);
|
||||
let args = get_wallet_subcommand(test_dir, wallet_name, args.clone());
|
||||
let mut config = initial_setup_wallet(test_dir, wallet_name);
|
||||
//unset chain type so it doesn't get reset
|
||||
config.chain_type = None;
|
||||
wallet_args::wallet_command(&args, config.clone(), client.clone())
|
||||
}
|
||||
|
||||
/// command line tests
|
||||
fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet::Error> {
|
||||
setup(test_dir);
|
||||
// Create a new proxy to simulate server and wallet responses
|
||||
let mut wallet_proxy: WalletProxy<LocalWalletClient, ExtKeychain> =
|
||||
WalletProxy::new(test_dir);
|
||||
let chain = wallet_proxy.chain.clone();
|
||||
|
||||
// load app yaml. If it don't exist, just say so and exit
|
||||
let yml = load_yaml!("../grin.yml");
|
||||
let app = App::from_yaml(yml);
|
||||
|
||||
// wallet init
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "init", "-h"];
|
||||
// should create new wallet file
|
||||
let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone());
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?;
|
||||
|
||||
// trying to init twice - should fail
|
||||
assert!(execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone()).is_err());
|
||||
let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone());
|
||||
|
||||
// add wallet to proxy
|
||||
//let wallet1 = test_framework::create_wallet(&format!("{}/wallet1", test_dir), client1.clone());
|
||||
let config1 = initial_setup_wallet(test_dir, "wallet1");
|
||||
let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?;
|
||||
wallet_proxy.add_wallet("wallet1", client1.get_send_instance(), wallet1.clone());
|
||||
|
||||
// Create wallet 2
|
||||
let client2 = LocalWalletClient::new("wallet2", wallet_proxy.tx.clone());
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?;
|
||||
|
||||
let config2 = initial_setup_wallet(test_dir, "wallet2");
|
||||
let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?;
|
||||
wallet_proxy.add_wallet("wallet2", client2.get_send_instance(), wallet2.clone());
|
||||
|
||||
// Set the wallet proxy listener running
|
||||
thread::spawn(move || {
|
||||
if let Err(e) = wallet_proxy.run() {
|
||||
error!("Wallet Proxy error: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
// Create some accounts in wallet 1
|
||||
let arg_vec = vec![
|
||||
"grin", "wallet", "-p", "password", "account", "-c", "mining",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"account",
|
||||
"-c",
|
||||
"account_1",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// Create some accounts in wallet 2
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"account",
|
||||
"-c",
|
||||
"account_1",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?;
|
||||
// already exists
|
||||
assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err());
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"account",
|
||||
"-c",
|
||||
"account_2",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?;
|
||||
|
||||
// let's see those accounts
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "account"];
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?;
|
||||
|
||||
// let's see those accounts
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "account"];
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?;
|
||||
|
||||
// Mine a bit into wallet 1 so we have something to send
|
||||
// (TODO: Be able to stop listeners so we can test this better)
|
||||
let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?;
|
||||
grin_wallet::controller::owner_single_use(wallet1.clone(), |api| {
|
||||
api.set_active_account("mining")?;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let mut bh = 10u64;
|
||||
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), bh as usize);
|
||||
|
||||
let very_long_message = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\
|
||||
This part should all be truncated";
|
||||
|
||||
// Update info and check
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// try a file exchange
|
||||
let file_name = format!("{}/tx1.part_tx", test_dir);
|
||||
let response_file_name = format!("{}/tx1.part_tx.response", test_dir);
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"send",
|
||||
"-m",
|
||||
"file",
|
||||
"-d",
|
||||
&file_name,
|
||||
"-g",
|
||||
very_long_message,
|
||||
"10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"account_1",
|
||||
"receive",
|
||||
"-i",
|
||||
&file_name,
|
||||
"-g",
|
||||
"Thanks, Yeast!",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?;
|
||||
|
||||
// shouldn't be allowed to receive twice
|
||||
assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err());
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"finalize",
|
||||
"-i",
|
||||
&response_file_name,
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
bh += 1;
|
||||
|
||||
let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?;
|
||||
|
||||
// Check our transaction log, should have 10 entries
|
||||
grin_wallet::controller::owner_single_use(wallet1.clone(), |api| {
|
||||
api.set_active_account("mining")?;
|
||||
let (refreshed, txs) = api.retrieve_txs(true, None, None)?;
|
||||
assert!(refreshed);
|
||||
assert_eq!(txs.len(), bh as usize);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), 10);
|
||||
bh += 10;
|
||||
|
||||
// update info for each
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "info"];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"account_1",
|
||||
"info",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet2", &client1, arg_vec)?;
|
||||
|
||||
// check results in wallet 2
|
||||
let wallet2 = instantiate_wallet(config2.clone(), client2.clone(), "password", "default")?;
|
||||
grin_wallet::controller::owner_single_use(wallet2.clone(), |api| {
|
||||
api.set_active_account("account_1")?;
|
||||
let (_, wallet1_info) = api.retrieve_summary_info(true, 1)?;
|
||||
assert_eq!(wallet1_info.last_confirmed_height, bh);
|
||||
assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// Self-send to same account, using smallest strategy
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"send",
|
||||
"-m",
|
||||
"file",
|
||||
"-d",
|
||||
&file_name,
|
||||
"-g",
|
||||
"Love, Yeast, Smallest",
|
||||
"-s",
|
||||
"smallest",
|
||||
"10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"receive",
|
||||
"-i",
|
||||
&file_name,
|
||||
"-g",
|
||||
"Thanks, Yeast!",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec.clone())?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"finalize",
|
||||
"-i",
|
||||
&response_file_name,
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
bh += 1;
|
||||
|
||||
// Check our transaction log, should have bh entries + one for the self receive
|
||||
let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?;
|
||||
|
||||
grin_wallet::controller::owner_single_use(wallet1.clone(), |api| {
|
||||
api.set_active_account("mining")?;
|
||||
let (refreshed, txs) = api.retrieve_txs(true, None, None)?;
|
||||
assert!(refreshed);
|
||||
assert_eq!(txs.len(), bh as usize + 1);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// Try using the self-send method, splitting up outputs for the fun of it
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"send",
|
||||
"-m",
|
||||
"self",
|
||||
"-d",
|
||||
"mining",
|
||||
"-g",
|
||||
"Self love",
|
||||
"-o",
|
||||
"3",
|
||||
"-s",
|
||||
"smallest",
|
||||
"10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
bh += 1;
|
||||
|
||||
// Check our transaction log, should have bh entries + 2 for the self receives
|
||||
let wallet1 = instantiate_wallet(config1.clone(), client1.clone(), "password", "default")?;
|
||||
|
||||
grin_wallet::controller::owner_single_use(wallet1.clone(), |api| {
|
||||
api.set_active_account("mining")?;
|
||||
let (refreshed, txs) = api.retrieve_txs(true, None, None)?;
|
||||
assert!(refreshed);
|
||||
assert_eq!(txs.len(), bh as usize + 2);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// Another file exchange, don't send, but unlock with repair command
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"send",
|
||||
"-m",
|
||||
"file",
|
||||
"-d",
|
||||
&file_name,
|
||||
"-g",
|
||||
"Ain't sending",
|
||||
"10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "check"];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// Another file exchange, cancel this time
|
||||
let arg_vec = vec![
|
||||
"grin",
|
||||
"wallet",
|
||||
"-p",
|
||||
"password",
|
||||
"-a",
|
||||
"mining",
|
||||
"send",
|
||||
"-m",
|
||||
"file",
|
||||
"-d",
|
||||
&file_name,
|
||||
"-g",
|
||||
"Ain't sending 2",
|
||||
"10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
let arg_vec = vec![
|
||||
"grin", "wallet", "-p", "password", "-a", "mining", "cancel", "-i", "26",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// txs and outputs (mostly spit out for a visual in test logs)
|
||||
let arg_vec = vec!["grin", "wallet", "-p", "password", "-a", "mining", "txs"];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// message output (mostly spit out for a visual in test logs)
|
||||
let arg_vec = vec![
|
||||
"grin", "wallet", "-p", "password", "-a", "mining", "txs", "-i", "10",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// txs and outputs (mostly spit out for a visual in test logs)
|
||||
let arg_vec = vec![
|
||||
"grin", "wallet", "-p", "password", "-a", "mining", "outputs",
|
||||
];
|
||||
execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?;
|
||||
|
||||
// let logging finish
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_command_line() {
|
||||
let test_dir = "target/test_output/command_line";
|
||||
if let Err(e) = command_line_test_impl(test_dir) {
|
||||
panic!("Libwallet Error: {} - {}", e, e.backtrace().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// 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.
|
||||
|
||||
//! Main for building the binary of a Grin peer-to-peer node.
|
||||
|
||||
#[macro_use]
|
||||
extern crate clap;
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
use crate::config::config::{SERVER_CONFIG_FILE_NAME, WALLET_CONFIG_FILE_NAME};
|
||||
use crate::core::global;
|
||||
use crate::util::init_logger;
|
||||
use clap::App;
|
||||
use grin_api as api;
|
||||
use grin_config as config;
|
||||
use grin_core as core;
|
||||
use grin_p2p as p2p;
|
||||
use grin_servers as servers;
|
||||
use grin_util as util;
|
||||
use std::process::exit;
|
||||
|
||||
mod cmd;
|
||||
|
||||
// include build information
|
||||
pub mod built_info {
|
||||
include!(concat!(env!("OUT_DIR"), "/built.rs"));
|
||||
}
|
||||
|
||||
pub fn info_strings() -> (String, String) {
|
||||
(
|
||||
format!(
|
||||
"This is Grin version {}{}, built for {} by {}.",
|
||||
built_info::PKG_VERSION,
|
||||
built_info::GIT_VERSION.map_or_else(|| "".to_owned(), |v| format!(" (git {})", v)),
|
||||
built_info::TARGET,
|
||||
built_info::RUSTC_VERSION,
|
||||
)
|
||||
.to_string(),
|
||||
format!(
|
||||
"Built with profile \"{}\", features \"{}\".",
|
||||
built_info::PROFILE,
|
||||
built_info::FEATURES_STR,
|
||||
)
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
fn log_build_info() {
|
||||
let (basic_info, detailed_info) = info_strings();
|
||||
info!("{}", basic_info);
|
||||
debug!("{}", detailed_info);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let exit_code = real_main();
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
fn real_main() -> i32 {
|
||||
let yml = load_yaml!("grin-wallet.yml");
|
||||
let args = App::from_yaml(yml).get_matches();
|
||||
let mut wallet_config = None;
|
||||
let mut node_config = None;
|
||||
|
||||
let chain_type = if args.is_present("floonet") {
|
||||
global::ChainTypes::Floonet
|
||||
} else if args.is_present("usernet") {
|
||||
global::ChainTypes::UserTesting
|
||||
} else {
|
||||
global::ChainTypes::Mainnet
|
||||
};
|
||||
|
||||
// Deal with configuration file creation
|
||||
match args.subcommand() {
|
||||
("wallet", Some(wallet_args)) => {
|
||||
// wallet init command should spit out its config file then continue
|
||||
// (if desired)
|
||||
if let ("init", Some(init_args)) = wallet_args.subcommand() {
|
||||
if init_args.is_present("here") {
|
||||
cmd::config_command_wallet(&chain_type, WALLET_CONFIG_FILE_NAME);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Load relevant config
|
||||
match args.subcommand() {
|
||||
// If it's a wallet command, try and load a wallet config file
|
||||
("wallet", Some(wallet_args)) => {
|
||||
let mut w = config::initial_setup_wallet(&chain_type).unwrap_or_else(|e| {
|
||||
panic!("Error loading wallet configuration: {}", e);
|
||||
});
|
||||
if !cmd::seed_exists(w.members.as_ref().unwrap().wallet.clone()) {
|
||||
if "init" == wallet_args.subcommand().0 || "recover" == wallet_args.subcommand().0 {
|
||||
} else {
|
||||
println!("Wallet seed file doesn't exist. Run `grin wallet init` first");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
let mut l = w.members.as_mut().unwrap().logging.clone().unwrap();
|
||||
l.tui_running = Some(false);
|
||||
init_logger(Some(l));
|
||||
info!(
|
||||
"Using wallet configuration file at {}",
|
||||
w.config_file_path.as_ref().unwrap().to_str().unwrap()
|
||||
);
|
||||
wallet_config = Some(w);
|
||||
}
|
||||
// When the subscommand is 'server' take into account the 'config_file' flag
|
||||
("server", Some(server_args)) => {
|
||||
if let Some(_path) = server_args.value_of("config_file") {
|
||||
node_config = Some(config::GlobalConfig::new(_path).unwrap_or_else(|e| {
|
||||
panic!("Error loading server configuration: {}", e);
|
||||
}));
|
||||
} else {
|
||||
node_config = Some(
|
||||
config::initial_setup_server(&chain_type).unwrap_or_else(|e| {
|
||||
panic!("Error loading server configuration: {}", e);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
// Otherwise load up the node config as usual
|
||||
_ => {
|
||||
node_config = Some(
|
||||
config::initial_setup_server(&chain_type).unwrap_or_else(|e| {
|
||||
panic!("Error loading server configuration: {}", e);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mut config) = node_config.clone() {
|
||||
let mut l = config.members.as_mut().unwrap().logging.clone().unwrap();
|
||||
let run_tui = config.members.as_mut().unwrap().server.run_tui;
|
||||
if let Some(true) = run_tui {
|
||||
l.log_to_stdout = false;
|
||||
l.tui_running = Some(true);
|
||||
}
|
||||
init_logger(Some(l));
|
||||
|
||||
global::set_mining_mode(config.members.unwrap().server.clone().chain_type);
|
||||
|
||||
if let Some(file_path) = &config.config_file_path {
|
||||
info!(
|
||||
"Using configuration file at {}",
|
||||
file_path.to_str().unwrap()
|
||||
);
|
||||
} else {
|
||||
info!("Node configuration file not found, using default");
|
||||
}
|
||||
}
|
||||
|
||||
log_build_info();
|
||||
|
||||
// Execute subcommand
|
||||
match args.subcommand() {
|
||||
// server commands and options
|
||||
("server", Some(server_args)) => {
|
||||
cmd::server_command(Some(server_args), node_config.unwrap())
|
||||
}
|
||||
|
||||
// client commands and options
|
||||
("client", Some(client_args)) => cmd::client_command(client_args, node_config.unwrap()),
|
||||
|
||||
// client commands and options
|
||||
("wallet", Some(wallet_args)) => cmd::wallet_command(wallet_args, wallet_config.unwrap()),
|
||||
|
||||
// If nothing is specified, try to just use the config file instead
|
||||
// this could possibly become the way to configure most things
|
||||
// with most command line options being phased out
|
||||
_ => cmd::server_command(None, node_config.unwrap()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
name: grin
|
||||
version: "1.0.1"
|
||||
about: Lightweight implementation of the MimbleWimble protocol.
|
||||
author: The Grin Team
|
||||
|
||||
args:
|
||||
- floonet:
|
||||
help: Run grin against the Floonet (as opposed to mainnet)
|
||||
long: floonet
|
||||
takes_value: false
|
||||
- usernet:
|
||||
help: Run grin as a local-only network. Doesn't block peer connections but will not connect to any peer or seed
|
||||
long: usernet
|
||||
takes_value: false
|
||||
subcommands:
|
||||
- server:
|
||||
about: Control the Grin server
|
||||
args:
|
||||
- config_file:
|
||||
help: Path to a grin-server.toml configuration file
|
||||
short: c
|
||||
long: config_file
|
||||
takes_value: true
|
||||
- port:
|
||||
help: Port to start the P2P server on
|
||||
short: p
|
||||
long: port
|
||||
takes_value: true
|
||||
- api_port:
|
||||
help: Port on which to start the api server (e.g. transaction pool api)
|
||||
short: api
|
||||
long: api_port
|
||||
takes_value: true
|
||||
- seed:
|
||||
help: Override seed node(s) to connect to
|
||||
short: s
|
||||
long: seed
|
||||
takes_value: true
|
||||
- wallet_url:
|
||||
help: The wallet listener to which mining rewards will be sent
|
||||
short: w
|
||||
long: wallet_url
|
||||
takes_value: true
|
||||
subcommands:
|
||||
- config:
|
||||
about: Generate a configuration grin-server.toml file in the current directory
|
||||
- run:
|
||||
about: Run the Grin server in this console
|
||||
- client:
|
||||
about: Communicates with the Grin server
|
||||
subcommands:
|
||||
- status:
|
||||
about: Current status of the Grin chain
|
||||
- listconnectedpeers:
|
||||
about: Print a list of currently connected peers
|
||||
- ban:
|
||||
about: Ban peer
|
||||
args:
|
||||
- peer:
|
||||
help: Peer ip and port (e.g. 10.12.12.13:13414)
|
||||
short: p
|
||||
long: peer
|
||||
required: true
|
||||
takes_value: true
|
||||
- unban:
|
||||
about: Unban peer
|
||||
args:
|
||||
- peer:
|
||||
help: Peer ip and port (e.g. 10.12.12.13:13414)
|
||||
short: p
|
||||
long: peer
|
||||
required: true
|
||||
takes_value: true
|
||||
- wallet:
|
||||
about: Wallet software for Grin
|
||||
args:
|
||||
- pass:
|
||||
help: Wallet passphrase used to encrypt wallet seed
|
||||
short: p
|
||||
long: pass
|
||||
takes_value: true
|
||||
- account:
|
||||
help: Wallet account to use for this operation
|
||||
short: a
|
||||
long: account
|
||||
takes_value: true
|
||||
default_value: default
|
||||
- data_dir:
|
||||
help: Directory in which to store wallet files
|
||||
short: dd
|
||||
long: data_dir
|
||||
takes_value: true
|
||||
- external:
|
||||
help: Listen on 0.0.0.0 interface to allow external connections (default is 127.0.0.1)
|
||||
short: e
|
||||
long: external
|
||||
takes_value: false
|
||||
- show_spent:
|
||||
help: Show spent outputs on wallet output commands
|
||||
short: s
|
||||
long: show_spent
|
||||
takes_value: false
|
||||
- api_server_address:
|
||||
help: Api address of running node on which to check inputs and post transactions
|
||||
short: r
|
||||
long: api_server_address
|
||||
takes_value: true
|
||||
subcommands:
|
||||
- account:
|
||||
about: List wallet accounts or create a new account
|
||||
args:
|
||||
- create:
|
||||
help: Create a new wallet account with provided name
|
||||
short: c
|
||||
long: create
|
||||
takes_value: true
|
||||
- listen:
|
||||
about: Runs the wallet in listening mode waiting for transactions
|
||||
args:
|
||||
- port:
|
||||
help: Port on which to run the wallet listener
|
||||
short: l
|
||||
long: port
|
||||
takes_value: true
|
||||
- method:
|
||||
help: Which method to use for communication
|
||||
short: m
|
||||
long: method
|
||||
possible_values:
|
||||
- http
|
||||
- keybase
|
||||
default_value: http
|
||||
takes_value: true
|
||||
- owner_api:
|
||||
about: Runs the wallet's local web API
|
||||
# Turned off, for now
|
||||
# - web:
|
||||
# about: Runs the local web wallet which can be accessed through a browser
|
||||
- send:
|
||||
about: Builds a transaction to send coins and sends to the specified listener directly
|
||||
args:
|
||||
- amount:
|
||||
help: Number of coins to send with optional fraction, e.g. 12.423
|
||||
index: 1
|
||||
- minimum_confirmations:
|
||||
help: Minimum number of confirmations required for an output to be spendable
|
||||
short: c
|
||||
long: min_conf
|
||||
default_value: "10"
|
||||
takes_value: true
|
||||
- selection_strategy:
|
||||
help: Coin/Output selection strategy.
|
||||
short: s
|
||||
long: selection
|
||||
possible_values:
|
||||
- all
|
||||
- smallest
|
||||
default_value: all
|
||||
takes_value: true
|
||||
- estimate_selection_strategies:
|
||||
help: Estimates all possible Coin/Output selection strategies.
|
||||
short: e
|
||||
long: estimate-selection
|
||||
- change_outputs:
|
||||
help: Number of change outputs to generate (mainly for testing)
|
||||
short: o
|
||||
long: change_outputs
|
||||
default_value: "1"
|
||||
takes_value: true
|
||||
- method:
|
||||
help: Method for sending this transaction
|
||||
short: m
|
||||
long: method
|
||||
possible_values:
|
||||
- http
|
||||
- file
|
||||
- self
|
||||
- keybase
|
||||
default_value: http
|
||||
takes_value: true
|
||||
- dest:
|
||||
help: Send the transaction to the provided server (start with http://) or save as file.
|
||||
short: d
|
||||
long: dest
|
||||
takes_value: true
|
||||
- fluff:
|
||||
help: Fluff the transaction (ignore Dandelion relay protocol)
|
||||
short: f
|
||||
long: fluff
|
||||
- message:
|
||||
help: Optional participant message to include
|
||||
short: g
|
||||
long: message
|
||||
takes_value: true
|
||||
- stored_tx:
|
||||
help: If present, use the previously stored Unconfirmed transaction with given id
|
||||
short: t
|
||||
long: stored_tx
|
||||
takes_value: true
|
||||
- receive:
|
||||
about: Processes a transaction file to accept a transfer from a sender
|
||||
args:
|
||||
- message:
|
||||
help: Optional participant message to include
|
||||
short: g
|
||||
long: message
|
||||
takes_value: true
|
||||
- input:
|
||||
help: Partial transaction to process, expects the sender's transaction file.
|
||||
short: i
|
||||
long: input
|
||||
takes_value: true
|
||||
- finalize:
|
||||
about: Processes a receiver's transaction file to finalize a transfer.
|
||||
args:
|
||||
- input:
|
||||
help: Partial transaction to process, expects the receiver's transaction file.
|
||||
short: i
|
||||
long: input
|
||||
takes_value: true
|
||||
- fluff:
|
||||
help: Fluff the transaction (ignore Dandelion relay protocol)
|
||||
short: f
|
||||
long: fluff
|
||||
- outputs:
|
||||
about: Raw wallet output info (list of outputs)
|
||||
- txs:
|
||||
about: Display transaction information
|
||||
args:
|
||||
- id:
|
||||
help: If specified, display transaction with given Id and all associated Inputs/Outputs
|
||||
short: i
|
||||
long: id
|
||||
takes_value: true
|
||||
- repost:
|
||||
about: Reposts a stored, completed but unconfirmed transaction to the chain, or dumps it to a file
|
||||
args:
|
||||
- id:
|
||||
help: Transaction ID containing the stored completed transaction
|
||||
short: i
|
||||
long: id
|
||||
takes_value: true
|
||||
- dumpfile:
|
||||
help: File name to duMp the transaction to instead of posting
|
||||
short: m
|
||||
long: dumpfile
|
||||
takes_value: true
|
||||
- fluff:
|
||||
help: Fluff the transaction (ignore Dandelion relay protocol)
|
||||
short: f
|
||||
long: fluff
|
||||
- cancel:
|
||||
about: Cancels an previously created transaction, freeing previously locked outputs for use again
|
||||
args:
|
||||
- id:
|
||||
help: The ID of the transaction to cancel
|
||||
short: i
|
||||
long: id
|
||||
takes_value: true
|
||||
- txid:
|
||||
help: The TxID UUID of the transaction to cancel
|
||||
short: t
|
||||
long: txid
|
||||
takes_value: true
|
||||
- info:
|
||||
about: Basic wallet contents summary
|
||||
args:
|
||||
- minimum_confirmations:
|
||||
help: Minimum number of confirmations required for an output to be spendable
|
||||
short: c
|
||||
long: min_conf
|
||||
default_value: "10"
|
||||
takes_value: true
|
||||
- init:
|
||||
about: Initialize a new wallet seed file and database
|
||||
args:
|
||||
- here:
|
||||
help: Create wallet files in the current directory instead of the default ~/.grin directory
|
||||
short: h
|
||||
long: here
|
||||
takes_value: false
|
||||
- short_wordlist:
|
||||
help: Generate a 12-word recovery phrase/seed instead of default 24
|
||||
short: s
|
||||
long: short_wordlist
|
||||
takes_value: false
|
||||
- recover:
|
||||
help: Initialize new wallet using a recovery phrase
|
||||
short: r
|
||||
long: recover
|
||||
takes_value: false
|
||||
- recover:
|
||||
about: Recover a wallet.seed file from a recovery phrase (default) or displays a recovery phrase for an existing seed file
|
||||
args:
|
||||
- display:
|
||||
help: Display wallet recovery phrase
|
||||
short: d
|
||||
long: display
|
||||
takes_value: false
|
||||
- restore:
|
||||
about: Restores a wallet contents from a seed file
|
||||
- check:
|
||||
about: Checks a wallet's outputs against a live node, repairing and restoring missing outputs if required
|
||||
@@ -0,0 +1,69 @@
|
||||
// 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.
|
||||
|
||||
/// File Output 'plugin' implementation
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use crate::adapters::util::{deserialize_slate, serialize_slate};
|
||||
use crate::libwallet::slate::Slate;
|
||||
use crate::libwallet::Error;
|
||||
use crate::{WalletCommAdapter, WalletConfig};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FileWalletCommAdapter {}
|
||||
|
||||
impl FileWalletCommAdapter {
|
||||
/// Create
|
||||
pub fn new() -> Box<dyn WalletCommAdapter> {
|
||||
Box::new(FileWalletCommAdapter {})
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for FileWalletCommAdapter {
|
||||
fn supports_sync(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn send_tx_sync(&self, _dest: &str, _slate: &Slate) -> Result<Slate, Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn send_tx_async(&self, dest: &str, slate: &Slate) -> Result<(), Error> {
|
||||
let mut pub_tx = File::create(dest)?;
|
||||
let slate_string = serialize_slate(slate);
|
||||
pub_tx.write_all(slate_string.as_bytes())?;
|
||||
pub_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn receive_tx_async(&self, params: &str) -> Result<Slate, Error> {
|
||||
let mut pub_tx_f = File::open(params)?;
|
||||
let mut content = String::new();
|
||||
pub_tx_f.read_to_string(&mut content)?;
|
||||
Ok(deserialize_slate(&content))
|
||||
}
|
||||
|
||||
fn listen(
|
||||
&self,
|
||||
_params: HashMap<String, String>,
|
||||
_config: WalletConfig,
|
||||
_passphrase: &str,
|
||||
_account: &str,
|
||||
_node_api_secret: Option<String>,
|
||||
) -> Result<(), Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// 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 crate::adapters::util::get_versioned_slate;
|
||||
use crate::api;
|
||||
use crate::controller;
|
||||
use crate::libwallet::slate::{Slate, VersionedSlate};
|
||||
use crate::libwallet::{Error, ErrorKind};
|
||||
use crate::{instantiate_wallet, HTTPNodeClient, WalletCommAdapter, WalletConfig};
|
||||
/// HTTP Wallet 'plugin' implementation
|
||||
use failure::ResultExt;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HTTPWalletCommAdapter {}
|
||||
|
||||
impl HTTPWalletCommAdapter {
|
||||
/// Create
|
||||
pub fn new() -> Box<dyn WalletCommAdapter> {
|
||||
Box::new(HTTPWalletCommAdapter {})
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for HTTPWalletCommAdapter {
|
||||
fn supports_sync(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_tx_sync(&self, dest: &str, slate: &Slate) -> Result<Slate, Error> {
|
||||
if &dest[..4] != "http" {
|
||||
let err_str = format!(
|
||||
"dest formatted as {} but send -d expected stdout or http://IP:port",
|
||||
dest
|
||||
);
|
||||
error!("{}", err_str,);
|
||||
Err(ErrorKind::Uri)?
|
||||
}
|
||||
let url = format!("{}/v1/wallet/foreign/receive_tx", dest);
|
||||
debug!("Posting transaction slate to {}", url);
|
||||
let slate = get_versioned_slate(slate);
|
||||
let res: Result<VersionedSlate, _> = api::client::post(url.as_str(), None, &slate);
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Posting transaction slate (is recipient listening?): {}", e);
|
||||
error!("{}", report);
|
||||
Err(ErrorKind::ClientCallback(report).into())
|
||||
}
|
||||
Ok(r) => Ok(r.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_tx_async(&self, _dest: &str, _slate: &Slate) -> Result<(), Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn receive_tx_async(&self, _params: &str) -> Result<Slate, Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn listen(
|
||||
&self,
|
||||
params: HashMap<String, String>,
|
||||
config: WalletConfig,
|
||||
passphrase: &str,
|
||||
account: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<(), Error> {
|
||||
let node_client = HTTPNodeClient::new(&config.check_node_api_http_addr, node_api_secret);
|
||||
let wallet = instantiate_wallet(config.clone(), node_client, passphrase, account)
|
||||
.context(ErrorKind::WalletSeedDecryption)?;
|
||||
let listen_addr = params.get("api_listen_addr").unwrap();
|
||||
let tls_conf = match params.get("certificate") {
|
||||
Some(s) => Some(api::TLSConfig::new(
|
||||
s.to_owned(),
|
||||
params.get("private_key").unwrap().to_owned(),
|
||||
)),
|
||||
None => None,
|
||||
};
|
||||
controller::foreign_listener(wallet.clone(), &listen_addr, tls_conf)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
// 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.
|
||||
|
||||
// Keybase Wallet Plugin
|
||||
|
||||
use crate::controller;
|
||||
use crate::libwallet::slate::{Slate, VersionedSlate};
|
||||
use crate::libwallet::slate_versions::v0::SlateV0;
|
||||
use crate::libwallet::{Error, ErrorKind};
|
||||
use crate::{instantiate_wallet, HTTPNodeClient, WalletCommAdapter, WalletConfig};
|
||||
use failure::ResultExt;
|
||||
use serde::Serialize;
|
||||
use serde_json::{from_str, json, to_string, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::str::from_utf8;
|
||||
use std::thread::sleep;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const TTL: u16 = 60; // TODO: Pass this as a parameter
|
||||
const LISTEN_SLEEP_DURATION: Duration = Duration::from_millis(5000);
|
||||
const POLL_SLEEP_DURATION: Duration = Duration::from_millis(1000);
|
||||
|
||||
// Which topic names to use for communication
|
||||
const SLATE_NEW: &str = "grin_slate_new";
|
||||
const SLATE_SIGNED: &str = "grin_slate_signed";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct KeybaseWalletCommAdapter {}
|
||||
|
||||
impl KeybaseWalletCommAdapter {
|
||||
/// Check if keybase is installed and return an adapter object.
|
||||
pub fn new() -> Box<WalletCommAdapter> {
|
||||
let mut proc = if cfg!(target_os = "windows") {
|
||||
Command::new("where")
|
||||
} else {
|
||||
Command::new("which")
|
||||
};
|
||||
proc.arg("keybase")
|
||||
.stdout(Stdio::null())
|
||||
.status()
|
||||
.expect("Keybase executable not found, make sure it is installed and in your PATH");
|
||||
|
||||
Box::new(KeybaseWalletCommAdapter {})
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a json object to the keybase process. Type `keybase chat api --help` for a list of available methods.
|
||||
fn api_send(payload: &str) -> Result<Value, Error> {
|
||||
let mut proc = Command::new("keybase");
|
||||
proc.args(&["chat", "api", "-m", &payload]);
|
||||
let output = proc.output().expect("No output");
|
||||
if !output.status.success() {
|
||||
error!(
|
||||
"keybase api fail: {} {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
|
||||
} else {
|
||||
let response: Value =
|
||||
from_str(from_utf8(&output.stdout).expect("Bad output")).expect("Bad output");
|
||||
let err_msg = format!("{}", response["error"]["message"]);
|
||||
if err_msg.len() > 0 && err_msg != "null" {
|
||||
error!("api_send got error: {}", err_msg);
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get keybase username
|
||||
fn whoami() -> Result<String, Error> {
|
||||
let mut proc = Command::new("keybase");
|
||||
proc.args(&["status", "-json"]);
|
||||
let output = proc.output().expect("No output");
|
||||
if !output.status.success() {
|
||||
error!(
|
||||
"keybase api fail: {} {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
|
||||
} else {
|
||||
let response: Value =
|
||||
from_str(from_utf8(&output.stdout).expect("Bad output")).expect("Bad output");
|
||||
let err_msg = format!("{}", response["error"]["message"]);
|
||||
if err_msg.len() > 0 && err_msg != "null" {
|
||||
error!("status query got error: {}", err_msg);
|
||||
}
|
||||
|
||||
let username = response["Username"].as_str();
|
||||
if let Some(s) = username {
|
||||
Ok(s.to_string())
|
||||
} else {
|
||||
error!("keybase username query fail");
|
||||
Err(ErrorKind::GenericError(
|
||||
"keybase username query fail".to_owned(),
|
||||
))?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all unread messages from a specific channel/topic and mark as read.
|
||||
fn read_from_channel(channel: &str, topic: &str) -> Result<Vec<String>, Error> {
|
||||
let payload = to_string(&json!({
|
||||
"method": "read",
|
||||
"params": {
|
||||
"options": {
|
||||
"channel": {
|
||||
"name": channel, "topic_type": "dev", "topic_name": topic
|
||||
},
|
||||
"unread_only": true, "peek": false
|
||||
},
|
||||
}
|
||||
}
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let response = api_send(&payload);
|
||||
if let Ok(res) = response {
|
||||
let mut unread: Vec<String> = Vec::new();
|
||||
for msg in res["result"]["messages"]
|
||||
.as_array()
|
||||
.unwrap_or(&vec![json!({})])
|
||||
.iter()
|
||||
{
|
||||
if (msg["msg"]["content"]["type"] == "text") && (msg["msg"]["unread"] == true) {
|
||||
let message = msg["msg"]["content"]["text"]["body"].as_str().unwrap_or("");
|
||||
unread.push(message.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(unread)
|
||||
} else {
|
||||
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
|
||||
}
|
||||
}
|
||||
|
||||
/// Get unread messages from all channels and mark as read.
|
||||
fn get_unread(topic: &str) -> Result<HashMap<String, String>, Error> {
|
||||
let payload = to_string(&json!({
|
||||
"method": "list",
|
||||
"params": {
|
||||
"options": {
|
||||
"topic_type": "dev",
|
||||
},
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let response = api_send(&payload);
|
||||
|
||||
if let Ok(res) = response {
|
||||
let mut channels = HashSet::new();
|
||||
// Unfortunately the response does not contain the message body
|
||||
// and a separate call is needed for each channel
|
||||
for msg in res["result"]["conversations"]
|
||||
.as_array()
|
||||
.unwrap_or(&vec![json!({})])
|
||||
.iter()
|
||||
{
|
||||
if (msg["unread"] == true) && (msg["channel"]["topic_name"] == topic) {
|
||||
let channel = msg["channel"]["name"].as_str().unwrap();
|
||||
channels.insert(channel.to_string());
|
||||
}
|
||||
}
|
||||
let mut unread: HashMap<String, String> = HashMap::new();
|
||||
for channel in channels.iter() {
|
||||
let messages = read_from_channel(channel, topic);
|
||||
if messages.is_err() {
|
||||
break;
|
||||
}
|
||||
for msg in messages.unwrap() {
|
||||
unread.insert(msg, channel.to_string());
|
||||
}
|
||||
}
|
||||
Ok(unread)
|
||||
} else {
|
||||
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a message to a keybase channel that self-destructs after ttl seconds.
|
||||
fn send<T: Serialize>(message: T, channel: &str, topic: &str, ttl: u16) -> bool {
|
||||
let seconds = format!("{}s", ttl);
|
||||
let serialized = to_string(&message).unwrap();
|
||||
let payload = to_string(&json!({
|
||||
"method": "send",
|
||||
"params": {
|
||||
"options": {
|
||||
"channel": {
|
||||
"name": channel, "topic_name": topic, "topic_type": "dev"
|
||||
},
|
||||
"message": {
|
||||
"body": serialized
|
||||
},
|
||||
"exploding_lifetime": seconds
|
||||
}
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let response = api_send(&payload);
|
||||
if let Ok(res) = response {
|
||||
match res["result"]["message"].as_str() {
|
||||
Some("message sent") => {
|
||||
debug!("Message sent to {}: {}", channel, serialized);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a notify to self that self-destructs after ttl minutes.
|
||||
fn notify(message: &str, channel: &str, ttl: u16) -> bool {
|
||||
let minutes = format!("{}m", ttl);
|
||||
let payload = to_string(&json!({
|
||||
"method": "send",
|
||||
"params": {
|
||||
"options": {
|
||||
"channel": {
|
||||
"name": channel
|
||||
},
|
||||
"message": {
|
||||
"body": message
|
||||
},
|
||||
"exploding_lifetime": minutes
|
||||
}
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let response = api_send(&payload);
|
||||
if let Ok(res) = response {
|
||||
match res["result"]["message"].as_str() {
|
||||
Some("message sent") => true,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Listen for a message from a specific channel with topic SLATE_SIGNED for nseconds and return the first valid slate.
|
||||
fn poll(nseconds: u64, channel: &str) -> Option<Slate> {
|
||||
let start = Instant::now();
|
||||
info!("Waiting for response message from @{}...", channel);
|
||||
while start.elapsed().as_secs() < nseconds {
|
||||
let unread = read_from_channel(channel, SLATE_SIGNED);
|
||||
for msg in unread.unwrap().iter() {
|
||||
let blob = from_str::<VersionedSlate>(msg);
|
||||
match blob {
|
||||
Ok(slate) => {
|
||||
let slate: Slate = slate.into();
|
||||
info!(
|
||||
"keybase response message received from @{}, tx uuid: {}",
|
||||
channel, slate.id,
|
||||
);
|
||||
return Some(slate);
|
||||
}
|
||||
Err(_) => (),
|
||||
}
|
||||
}
|
||||
sleep(POLL_SLEEP_DURATION);
|
||||
}
|
||||
error!(
|
||||
"No response from @{} in {} seconds. Grin send failed!",
|
||||
channel, nseconds
|
||||
);
|
||||
None
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for KeybaseWalletCommAdapter {
|
||||
fn supports_sync(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// Send a slate to a keybase username then wait for a response for TTL seconds.
|
||||
fn send_tx_sync(&self, addr: &str, slate: &Slate) -> Result<Slate, Error> {
|
||||
// Limit only one recipient
|
||||
if addr.matches(",").count() > 0 {
|
||||
error!("Only one recipient is supported!");
|
||||
return Err(ErrorKind::GenericError("Tx rejected".to_owned()))?;
|
||||
}
|
||||
|
||||
let id = slate.id;
|
||||
|
||||
// Send original slate to recipient with the SLATE_NEW topic
|
||||
match send(&slate, addr, SLATE_NEW, TTL) {
|
||||
true => (),
|
||||
false => {
|
||||
return Err(ErrorKind::ClientCallback(
|
||||
"Posting transaction slate".to_owned(),
|
||||
))?
|
||||
}
|
||||
}
|
||||
info!("tx request has been sent to @{}, tx uuid: {}", addr, id);
|
||||
// Wait for response from recipient with SLATE_SIGNED topic
|
||||
match poll(TTL as u64, addr) {
|
||||
Some(slate) => return Ok(slate),
|
||||
None => {
|
||||
return Err(ErrorKind::ClientCallback(
|
||||
"Receiving reply from recipient".to_owned(),
|
||||
))?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a transaction asynchronously (result will be returned via the listener)
|
||||
fn send_tx_async(&self, _addr: &str, _slate: &Slate) -> Result<(), Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
/// Receive a transaction async. (Actually just read it from wherever and return the slate)
|
||||
fn receive_tx_async(&self, _params: &str) -> Result<Slate, Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
/// Start a listener, passing received messages to the wallet api directly
|
||||
#[allow(unreachable_code)]
|
||||
fn listen(
|
||||
&self,
|
||||
_params: HashMap<String, String>,
|
||||
config: WalletConfig,
|
||||
passphrase: &str,
|
||||
account: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<(), Error> {
|
||||
let node_client = HTTPNodeClient::new(&config.check_node_api_http_addr, node_api_secret);
|
||||
let wallet = instantiate_wallet(config.clone(), node_client, passphrase, account)
|
||||
.context(ErrorKind::WalletSeedDecryption)?;
|
||||
|
||||
info!("Listening for transactions on keybase ...");
|
||||
loop {
|
||||
// listen for messages from all channels with topic SLATE_NEW
|
||||
let unread = get_unread(SLATE_NEW);
|
||||
if unread.is_err() {
|
||||
error!("Listening exited for some keybase api failure");
|
||||
break;
|
||||
}
|
||||
for (msg, channel) in &unread.unwrap() {
|
||||
let blob = from_str::<VersionedSlate>(msg);
|
||||
match blob {
|
||||
Ok(message) => {
|
||||
let mut slate: Slate = message.clone().into();
|
||||
let tx_uuid = slate.id;
|
||||
|
||||
// Reject multiple recipients channel for safety
|
||||
{
|
||||
if channel.matches(",").count() > 1 {
|
||||
error!(
|
||||
"Incoming tx initiated on channel \"{}\" is rejected, multiple recipients channel! amount: {}(g), tx uuid: {}",
|
||||
channel,
|
||||
slate.amount as f64 / 1000000000.0,
|
||||
tx_uuid,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"tx initiated on channel \"{}\", to send you {}(g). tx uuid: {}",
|
||||
channel,
|
||||
slate.amount as f64 / 1000000000.0,
|
||||
tx_uuid,
|
||||
);
|
||||
match controller::foreign_single_use(wallet.clone(), |api| {
|
||||
if let Err(e) = api.verify_slate_messages(&slate) {
|
||||
error!("Error validating participant messages: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
api.receive_tx(&mut slate, None, None)?;
|
||||
Ok(())
|
||||
}) {
|
||||
// Reply to the same channel with topic SLATE_SIGNED
|
||||
Ok(_) => {
|
||||
let success = match message {
|
||||
// Send the same version of slate that was sent to us
|
||||
VersionedSlate::V0(_) => {
|
||||
send(SlateV0::from(slate), channel, SLATE_SIGNED, TTL)
|
||||
}
|
||||
VersionedSlate::V1(_) => {
|
||||
send(slate, channel, SLATE_SIGNED, TTL)
|
||||
}
|
||||
};
|
||||
|
||||
if success {
|
||||
notify_on_receive(
|
||||
config.keybase_notify_ttl.unwrap_or(1440),
|
||||
channel.to_string(),
|
||||
tx_uuid.to_string(),
|
||||
);
|
||||
debug!("Returned slate to @{} via keybase", channel);
|
||||
} else {
|
||||
error!("Failed to return slate to @{} via keybase. Incoming tx failed", channel);
|
||||
}
|
||||
}
|
||||
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Error on receiving tx via keybase: {}. Incoming tx failed",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => debug!("Failed to deserialize keybase message: {}", msg),
|
||||
}
|
||||
}
|
||||
sleep(LISTEN_SLEEP_DURATION);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Notify in keybase on receiving a transaction
|
||||
fn notify_on_receive(keybase_notify_ttl: u16, channel: String, tx_uuid: String) {
|
||||
if keybase_notify_ttl > 0 {
|
||||
let my_username = whoami();
|
||||
if let Ok(username) = my_username {
|
||||
let split = channel.split(",");
|
||||
let vec: Vec<&str> = split.collect();
|
||||
if vec.len() > 1 {
|
||||
let receiver = username;
|
||||
let sender = if vec[0] == receiver {
|
||||
vec[1]
|
||||
} else {
|
||||
if vec[1] != receiver {
|
||||
error!("keybase - channel doesn't include my username! channel: {}, username: {}",
|
||||
channel, receiver
|
||||
);
|
||||
}
|
||||
vec[0]
|
||||
};
|
||||
|
||||
let msg = format!(
|
||||
"[grin wallet notice]: \
|
||||
you could have some coins received from @{}\n\
|
||||
Transaction Id: {}",
|
||||
sender, tx_uuid
|
||||
);
|
||||
notify(&msg, &receiver, keybase_notify_ttl);
|
||||
info!(
|
||||
"tx from @{} is done, please check on grin wallet. tx uuid: {}",
|
||||
sender, tx_uuid,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
error!("keybase notification fail on whoami query");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// 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.
|
||||
|
||||
mod file;
|
||||
mod http;
|
||||
mod keybase;
|
||||
mod null;
|
||||
pub mod util;
|
||||
|
||||
pub use self::file::FileWalletCommAdapter;
|
||||
pub use self::http::HTTPWalletCommAdapter;
|
||||
pub use self::keybase::KeybaseWalletCommAdapter;
|
||||
pub use self::null::NullWalletCommAdapter;
|
||||
|
||||
use crate::libwallet::slate::Slate;
|
||||
use crate::libwallet::Error;
|
||||
use crate::WalletConfig;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Encapsulate wallet to wallet communication functions
|
||||
pub trait WalletCommAdapter {
|
||||
/// Whether this adapter supports sync mode
|
||||
fn supports_sync(&self) -> bool;
|
||||
|
||||
/// Send a transaction slate to another listening wallet and return result
|
||||
/// TODO: Probably need a slate wrapper type
|
||||
fn send_tx_sync(&self, addr: &str, slate: &Slate) -> Result<Slate, Error>;
|
||||
|
||||
/// Send a transaction asynchronously (result will be returned via the listener)
|
||||
fn send_tx_async(&self, addr: &str, slate: &Slate) -> Result<(), Error>;
|
||||
|
||||
/// Receive a transaction async. (Actually just read it from wherever and return the slate)
|
||||
fn receive_tx_async(&self, params: &str) -> Result<Slate, Error>;
|
||||
|
||||
/// Start a listener, passing received messages to the wallet api directly
|
||||
/// Takes a wallet config for now to avoid needing all sorts of awkward
|
||||
/// type parameters on this trait
|
||||
fn listen(
|
||||
&self,
|
||||
params: HashMap<String, String>,
|
||||
config: WalletConfig,
|
||||
passphrase: &str,
|
||||
account: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<(), Error>;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// 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.
|
||||
|
||||
/// Null Output 'plugin' implementation
|
||||
use crate::libwallet::slate::Slate;
|
||||
use crate::libwallet::Error;
|
||||
use crate::{WalletCommAdapter, WalletConfig};
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NullWalletCommAdapter {}
|
||||
|
||||
impl NullWalletCommAdapter {
|
||||
/// Create
|
||||
pub fn new() -> Box<NullWalletCommAdapter> {
|
||||
Box::new(NullWalletCommAdapter {})
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for NullWalletCommAdapter {
|
||||
fn supports_sync(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_tx_sync(&self, _dest: &str, slate: &Slate) -> Result<Slate, Error> {
|
||||
Ok(slate.clone())
|
||||
}
|
||||
|
||||
fn send_tx_async(&self, _dest: &str, _slate: &Slate) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn receive_tx_async(&self, _params: &str) -> Result<Slate, Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn listen(
|
||||
&self,
|
||||
_params: HashMap<String, String>,
|
||||
_config: WalletConfig,
|
||||
_passphrase: &str,
|
||||
_account: &str,
|
||||
_node_api_secret: Option<String>,
|
||||
) -> Result<(), Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::libwallet::slate::{Slate, VersionedSlate};
|
||||
use crate::libwallet::slate_versions::v0::SlateV0;
|
||||
use crate::libwallet::ErrorKind;
|
||||
use serde_json as json;
|
||||
|
||||
pub fn get_versioned_slate(slate: &Slate) -> VersionedSlate {
|
||||
let slate = slate.clone();
|
||||
match slate.version {
|
||||
0 => VersionedSlate::V0(SlateV0::from(slate)),
|
||||
_ => VersionedSlate::V1(slate),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize_slate(slate: &Slate) -> String {
|
||||
json::to_string(&get_versioned_slate(slate)).unwrap()
|
||||
}
|
||||
|
||||
pub fn deserialize_slate(raw_slate: &str) -> Slate {
|
||||
let versioned_slate: VersionedSlate = json::from_str(&raw_slate)
|
||||
.map_err(|err| ErrorKind::Format(err.to_string()))
|
||||
.unwrap();
|
||||
versioned_slate.into()
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
// 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 crate::util::{Mutex, ZeroingString};
|
||||
use std::collections::HashMap;
|
||||
/// Grin wallet command-line function implementations
|
||||
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::error::{Error, ErrorKind};
|
||||
use crate::{controller, display, HTTPNodeClient, WalletConfig, WalletInst, WalletSeed};
|
||||
use crate::{
|
||||
FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter, LMDBBackend,
|
||||
NodeClient, NullWalletCommAdapter,
|
||||
};
|
||||
|
||||
/// Arguments common to all wallet commands
|
||||
#[derive(Clone)]
|
||||
pub struct GlobalArgs {
|
||||
pub account: String,
|
||||
pub node_api_secret: Option<String>,
|
||||
pub show_spent: bool,
|
||||
pub password: Option<ZeroingString>,
|
||||
pub tls_conf: Option<TLSConfig>,
|
||||
}
|
||||
|
||||
/// Arguments for init command
|
||||
pub struct InitArgs {
|
||||
/// BIP39 recovery phrase length
|
||||
pub list_length: usize,
|
||||
pub password: ZeroingString,
|
||||
pub config: WalletConfig,
|
||||
pub recovery_phrase: Option<ZeroingString>,
|
||||
pub restore: bool,
|
||||
}
|
||||
|
||||
pub fn init(g_args: &GlobalArgs, args: InitArgs) -> Result<(), Error> {
|
||||
WalletSeed::init_file(
|
||||
&args.config,
|
||||
args.list_length,
|
||||
args.recovery_phrase,
|
||||
&args.password,
|
||||
)?;
|
||||
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");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Argument for recover
|
||||
pub struct RecoverArgs {
|
||||
pub recovery_phrase: Option<ZeroingString>,
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Arguments for listen command
|
||||
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());
|
||||
}
|
||||
let adapter = match args.method.as_str() {
|
||||
"http" => HTTPWalletCommAdapter::new(),
|
||||
"keybase" => KeybaseWalletCommAdapter::new(),
|
||||
_ => NullWalletCommAdapter::new(),
|
||||
};
|
||||
|
||||
let res = adapter.listen(
|
||||
params,
|
||||
config.clone(),
|
||||
&g_args.password.clone().unwrap(),
|
||||
&g_args.account,
|
||||
g_args.node_api_secret.clone(),
|
||||
);
|
||||
if let Err(e) = res {
|
||||
return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn owner_api(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
config: &WalletConfig,
|
||||
g_args: &GlobalArgs,
|
||||
) -> Result<(), Error> {
|
||||
let res = controller::owner_listener(
|
||||
wallet,
|
||||
config.owner_api_listen_addr().as_str(),
|
||||
g_args.node_api_secret.clone(),
|
||||
g_args.tls_conf.clone(),
|
||||
config.owner_api_include_foreign.clone(),
|
||||
);
|
||||
if let Err(e) = res {
|
||||
return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Arguments for account command
|
||||
pub struct AccountArgs {
|
||||
pub create: Option<String>,
|
||||
}
|
||||
|
||||
pub fn account(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: AccountArgs,
|
||||
) -> Result<(), Error> {
|
||||
if args.create.is_none() {
|
||||
let res = controller::owner_single_use(wallet, |api| {
|
||||
let acct_mappings = api.accounts()?;
|
||||
// give logging thread a moment to catch up
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
display::accounts(acct_mappings);
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = res {
|
||||
error!("Error listing accounts: {}", e);
|
||||
return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into());
|
||||
}
|
||||
} else {
|
||||
let label = args.create.unwrap();
|
||||
let res = controller::owner_single_use(wallet, |api| {
|
||||
api.create_account_path(&label)?;
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
info!("Account: '{}' Created!", label);
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = res {
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
error!("Error creating account '{}': {}", label, e);
|
||||
return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Arguments for the send command
|
||||
pub struct SendArgs {
|
||||
pub amount: u64,
|
||||
pub message: Option<String>,
|
||||
pub minimum_confirmations: u64,
|
||||
pub selection_strategy: String,
|
||||
pub estimate_selection_strategies: bool,
|
||||
pub method: String,
|
||||
pub dest: String,
|
||||
pub change_outputs: usize,
|
||||
pub fluff: bool,
|
||||
pub max_outputs: usize,
|
||||
}
|
||||
|
||||
pub fn send(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: SendArgs,
|
||||
dark_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
if args.estimate_selection_strategies {
|
||||
let strategies = vec!["smallest", "all"]
|
||||
.into_iter()
|
||||
.map(|strategy| {
|
||||
let (total, fee) = api
|
||||
.estimate_initiate_tx(
|
||||
None,
|
||||
args.amount,
|
||||
args.minimum_confirmations,
|
||||
args.max_outputs,
|
||||
args.change_outputs,
|
||||
strategy == "all",
|
||||
)
|
||||
.unwrap();
|
||||
(strategy, total, fee)
|
||||
})
|
||||
.collect();
|
||||
display::estimate(args.amount, strategies, dark_scheme);
|
||||
} else {
|
||||
let result = api.initiate_tx(
|
||||
None,
|
||||
args.amount,
|
||||
args.minimum_confirmations,
|
||||
args.max_outputs,
|
||||
args.change_outputs,
|
||||
args.selection_strategy == "all",
|
||||
args.message.clone(),
|
||||
);
|
||||
let (mut slate, lock_fn) = match result {
|
||||
Ok(s) => {
|
||||
info!(
|
||||
"Tx created: {} grin to {} (strategy '{}')",
|
||||
core::amount_to_hr_string(args.amount, false),
|
||||
args.dest,
|
||||
args.selection_strategy,
|
||||
);
|
||||
s
|
||||
}
|
||||
Err(e) => {
|
||||
info!("Tx not created: {}", e);
|
||||
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, lock_fn)?;
|
||||
if args.method == "self" {
|
||||
controller::foreign_single_use(wallet, |api| {
|
||||
api.receive_tx(&mut slate, Some(&args.dest), None)?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
if let Err(e) = api.verify_slate_messages(&slate) {
|
||||
error!("Error validating participant messages: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
api.finalize_tx(&mut slate)?;
|
||||
} else {
|
||||
adapter.send_tx_async(&args.dest, &slate)?;
|
||||
api.tx_lock_outputs(&slate, lock_fn)?;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Receive command argument
|
||||
pub struct ReceiveArgs {
|
||||
pub input: String,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
pub fn receive(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
g_args: &GlobalArgs,
|
||||
args: ReceiveArgs,
|
||||
) -> Result<(), Error> {
|
||||
let adapter = FileWalletCommAdapter::new();
|
||||
let mut slate = adapter.receive_tx_async(&args.input)?;
|
||||
controller::foreign_single_use(wallet, |api| {
|
||||
if let Err(e) = api.verify_slate_messages(&slate) {
|
||||
error!("Error validating participant messages: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
api.receive_tx(&mut slate, Some(&g_args.account), args.message.clone())?;
|
||||
Ok(())
|
||||
})?;
|
||||
let send_tx = format!("{}.response", args.input);
|
||||
adapter.send_tx_async(&send_tx, &slate)?;
|
||||
info!(
|
||||
"Response file {}.response generated, sending it back to the transaction originator.",
|
||||
args.input
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Finalize command args
|
||||
pub struct FinalizeArgs {
|
||||
pub input: String,
|
||||
pub fluff: bool,
|
||||
}
|
||||
|
||||
pub fn finalize(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: FinalizeArgs,
|
||||
) -> Result<(), Error> {
|
||||
let adapter = FileWalletCommAdapter::new();
|
||||
let mut slate = adapter.receive_tx_async(&args.input)?;
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
if let Err(e) = api.verify_slate_messages(&slate) {
|
||||
error!("Error validating participant messages: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = api.finalize_tx(&mut slate).expect("Finalize failed");
|
||||
|
||||
let result = api.post_tx(&slate.tx, args.fluff);
|
||||
match result {
|
||||
Ok(_) => {
|
||||
info!("Transaction sent successfully, check the wallet again for confirmation.");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Tx not sent: {}", e);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Info command args
|
||||
pub struct InfoArgs {
|
||||
pub minimum_confirmations: u64,
|
||||
}
|
||||
|
||||
pub fn info(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
g_args: &GlobalArgs,
|
||||
args: InfoArgs,
|
||||
dark_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
let (validated, wallet_info) =
|
||||
api.retrieve_summary_info(true, args.minimum_confirmations)?;
|
||||
display::info(&g_args.account, &wallet_info, validated, dark_scheme);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn outputs(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
g_args: &GlobalArgs,
|
||||
dark_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
let (height, _) = api.node_height()?;
|
||||
let (validated, outputs) = api.retrieve_outputs(g_args.show_spent, true, None)?;
|
||||
display::outputs(&g_args.account, height, validated, outputs, dark_scheme)?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Txs command args
|
||||
pub struct TxsArgs {
|
||||
pub id: Option<u32>,
|
||||
}
|
||||
|
||||
pub fn txs(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
g_args: &GlobalArgs,
|
||||
args: TxsArgs,
|
||||
dark_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
let (height, _) = api.node_height()?;
|
||||
let (validated, txs) = api.retrieve_txs(true, args.id, None)?;
|
||||
let include_status = !args.id.is_some();
|
||||
display::txs(
|
||||
&g_args.account,
|
||||
height,
|
||||
validated,
|
||||
&txs,
|
||||
include_status,
|
||||
dark_scheme,
|
||||
)?;
|
||||
// if given a particular transaction id, also get and display associated
|
||||
// inputs/outputs and messages
|
||||
if args.id.is_some() {
|
||||
let (_, outputs) = api.retrieve_outputs(true, false, args.id)?;
|
||||
display::outputs(&g_args.account, height, validated, outputs, dark_scheme)?;
|
||||
// should only be one here, but just in case
|
||||
for tx in txs {
|
||||
display::tx_messages(&tx, dark_scheme)?;
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repost
|
||||
pub struct RepostArgs {
|
||||
pub id: u32,
|
||||
pub dump_file: Option<String>,
|
||||
pub fluff: bool,
|
||||
}
|
||||
|
||||
pub fn repost(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: RepostArgs,
|
||||
) -> Result<(), Error> {
|
||||
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])?;
|
||||
if stored_tx.is_none() {
|
||||
error!(
|
||||
"Transaction with id {} does not have transaction data. Not reposting.",
|
||||
args.id
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
match args.dump_file {
|
||||
None => {
|
||||
if txs[0].confirmed {
|
||||
error!(
|
||||
"Transaction with id {} is confirmed. Not reposting.",
|
||||
args.id
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
api.post_tx(&stored_tx.unwrap(), args.fluff)?;
|
||||
info!("Reposted transaction at {}", args.id);
|
||||
return Ok(());
|
||||
}
|
||||
Some(f) => {
|
||||
let mut tx_file = File::create(f.clone())?;
|
||||
tx_file.write_all(json::to_string(&stored_tx).unwrap().as_bytes())?;
|
||||
tx_file.sync_all()?;
|
||||
info!("Dumped transaction data for tx {} to {}", args.id, f);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancel
|
||||
pub struct CancelArgs {
|
||||
pub tx_id: Option<u32>,
|
||||
pub tx_slate_id: Option<Uuid>,
|
||||
pub tx_id_string: String,
|
||||
}
|
||||
|
||||
pub fn cancel(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: CancelArgs,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
let result = api.cancel_tx(args.tx_id, args.tx_slate_id);
|
||||
match result {
|
||||
Ok(_) => {
|
||||
info!("Transaction {} Cancelled", args.tx_id_string);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
error!("TX Cancellation failed: {}", e);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restore(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
let result = api.restore();
|
||||
match result {
|
||||
Ok(_) => {
|
||||
warn!("Wallet restore complete",);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Wallet restore failed: {}", e);
|
||||
error!("Backtrace: {}", e.backtrace().unwrap());
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn check_repair(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
) -> Result<(), Error> {
|
||||
controller::owner_single_use(wallet.clone(), |api| {
|
||||
warn!("Starting wallet check...",);
|
||||
warn!("Updating all wallet outputs, please wait ...",);
|
||||
let result = api.check_repair();
|
||||
match result {
|
||||
Ok(_) => {
|
||||
warn!("Wallet check complete",);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Wallet check failed: {}", e);
|
||||
error!("Backtrace: {}", e.backtrace().unwrap());
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
// 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.
|
||||
|
||||
//! Controller for wallet.. instantiates and handles listeners (or single-run
|
||||
//! invocations) as needed.
|
||||
//! Still experimental
|
||||
use crate::adapters::util::get_versioned_slate;
|
||||
use crate::adapters::{FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter};
|
||||
use crate::api::{ApiServer, BasicAuthMiddleware, Handler, ResponseFuture, Router, TLSConfig};
|
||||
use crate::core::core;
|
||||
use crate::core::core::Transaction;
|
||||
use crate::keychain::Keychain;
|
||||
use crate::libwallet::api::{APIForeign, APIOwner};
|
||||
use crate::libwallet::slate::{Slate, VersionedSlate};
|
||||
use crate::libwallet::types::{
|
||||
CbData, NodeClient, OutputData, SendTXArgs, TxLogEntry, WalletBackend, WalletInfo,
|
||||
};
|
||||
use crate::libwallet::{Error, ErrorKind};
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::to_base64;
|
||||
use crate::util::Mutex;
|
||||
use failure::ResultExt;
|
||||
use futures::future::{err, ok};
|
||||
use futures::{Future, Stream};
|
||||
use hyper::{Body, Request, Response, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use url::form_urlencoded;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Instantiate wallet Owner API for a single-use (command line) call
|
||||
/// Return a function containing a loaded API context to call
|
||||
pub fn owner_single_use<F, T: ?Sized, C, K>(wallet: Arc<Mutex<T>>, f: F) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
F: FnOnce(&mut APIOwner<T, C, K>) -> Result<(), Error>,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
f(&mut APIOwner::new(wallet.clone()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Instantiate wallet Foreign API for a single-use (command line) call
|
||||
/// Return a function containing a loaded API context to call
|
||||
pub fn foreign_single_use<F, T: ?Sized, C, K>(wallet: Arc<Mutex<T>>, f: F) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
F: FnOnce(&mut APIForeign<T, C, K>) -> Result<(), Error>,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
f(&mut APIForeign::new(wallet.clone()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Listener version, providing same API but listening for requests on a
|
||||
/// port and wrapping the calls
|
||||
pub fn owner_listener<T: ?Sized, C, K>(
|
||||
wallet: Arc<Mutex<T>>,
|
||||
addr: &str,
|
||||
api_secret: Option<String>,
|
||||
tls_config: Option<TLSConfig>,
|
||||
owner_api_include_foreign: Option<bool>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
OwnerAPIHandler<T, C, K>: Handler,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
let api_handler = OwnerAPIHandler::new(wallet.clone());
|
||||
|
||||
let mut router = Router::new();
|
||||
if api_secret.is_some() {
|
||||
let api_basic_auth =
|
||||
"Basic ".to_string() + &to_base64(&("grin:".to_string() + &api_secret.unwrap()));
|
||||
let basic_realm = "Basic realm=GrinOwnerAPI".to_string();
|
||||
let basic_auth_middleware = Arc::new(BasicAuthMiddleware::new(api_basic_auth, basic_realm));
|
||||
router.add_middleware(basic_auth_middleware);
|
||||
}
|
||||
router
|
||||
.add_route("/v1/wallet/owner/**", Arc::new(api_handler))
|
||||
.map_err(|_| ErrorKind::GenericError("Router failed to add route".to_string()))?;
|
||||
|
||||
// If so configured, add the foreign API to the same port
|
||||
if owner_api_include_foreign.unwrap_or(false) {
|
||||
info!("Starting HTTP Foreign API on Owner server at {}.", addr);
|
||||
let foreign_api_handler = ForeignAPIHandler::new(wallet.clone());
|
||||
router
|
||||
.add_route("/v1/wallet/foreign/**", Arc::new(foreign_api_handler))
|
||||
.map_err(|_| ErrorKind::GenericError("Router failed to add route".to_string()))?;
|
||||
}
|
||||
|
||||
let mut apis = ApiServer::new();
|
||||
info!("Starting HTTP Owner API server at {}.", addr);
|
||||
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
|
||||
let api_thread =
|
||||
apis.start(socket_addr, router, tls_config)
|
||||
.context(ErrorKind::GenericError(
|
||||
"API thread failed to start".to_string(),
|
||||
))?;
|
||||
api_thread
|
||||
.join()
|
||||
.map_err(|e| ErrorKind::GenericError(format!("API thread panicked :{:?}", e)).into())
|
||||
}
|
||||
|
||||
/// Listener version, providing same API but listening for requests on a
|
||||
/// port and wrapping the calls
|
||||
pub fn foreign_listener<T: ?Sized, C, K>(
|
||||
wallet: Arc<Mutex<T>>,
|
||||
addr: &str,
|
||||
tls_config: Option<TLSConfig>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
let api_handler = ForeignAPIHandler::new(wallet);
|
||||
|
||||
let mut router = Router::new();
|
||||
router
|
||||
.add_route("/v1/wallet/foreign/**", Arc::new(api_handler))
|
||||
.map_err(|_| ErrorKind::GenericError("Router failed to add route".to_string()))?;
|
||||
|
||||
let mut apis = ApiServer::new();
|
||||
warn!("Starting HTTP Foreign listener API server at {}.", addr);
|
||||
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
|
||||
let api_thread =
|
||||
apis.start(socket_addr, router, tls_config)
|
||||
.context(ErrorKind::GenericError(
|
||||
"API thread failed to start".to_string(),
|
||||
))?;
|
||||
warn!("HTTP Foreign listener started.");
|
||||
|
||||
api_thread
|
||||
.join()
|
||||
.map_err(|e| ErrorKind::GenericError(format!("API thread panicked :{:?}", e)).into())
|
||||
}
|
||||
|
||||
type WalletResponseFuture = Box<dyn Future<Item = Response<Body>, Error = Error> + Send>;
|
||||
|
||||
/// API Handler/Wrapper for owner functions
|
||||
pub struct OwnerAPIHandler<T: ?Sized, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
/// Wallet instance
|
||||
pub wallet: Arc<Mutex<T>>,
|
||||
phantom: PhantomData<K>,
|
||||
phantom_c: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T: ?Sized, C, K> OwnerAPIHandler<T, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
/// Create a new owner API handler for GET methods
|
||||
pub fn new(wallet: Arc<Mutex<T>>) -> OwnerAPIHandler<T, C, K> {
|
||||
OwnerAPIHandler {
|
||||
wallet,
|
||||
phantom: PhantomData,
|
||||
phantom_c: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retrieve_outputs(
|
||||
&self,
|
||||
req: &Request<Body>,
|
||||
api: APIOwner<T, C, K>,
|
||||
) -> Result<(bool, Vec<(OutputData, pedersen::Commitment)>), Error> {
|
||||
let mut update_from_node = false;
|
||||
let mut id = None;
|
||||
let mut show_spent = false;
|
||||
let params = parse_params(req);
|
||||
|
||||
if let Some(_) = params.get("refresh") {
|
||||
update_from_node = true;
|
||||
}
|
||||
if let Some(_) = params.get("show_spent") {
|
||||
show_spent = true;
|
||||
}
|
||||
if let Some(ids) = params.get("tx_id") {
|
||||
if let Some(x) = ids.first() {
|
||||
id = Some(x.parse().unwrap());
|
||||
}
|
||||
}
|
||||
api.retrieve_outputs(show_spent, update_from_node, id)
|
||||
}
|
||||
|
||||
pub fn retrieve_txs(
|
||||
&self,
|
||||
req: &Request<Body>,
|
||||
api: APIOwner<T, C, K>,
|
||||
) -> Result<(bool, Vec<TxLogEntry>), Error> {
|
||||
let mut tx_id = None;
|
||||
let mut tx_slate_id = None;
|
||||
let mut update_from_node = false;
|
||||
|
||||
let params = parse_params(req);
|
||||
|
||||
if let Some(_) = params.get("refresh") {
|
||||
update_from_node = true;
|
||||
}
|
||||
if let Some(ids) = params.get("id") {
|
||||
if let Some(x) = ids.first() {
|
||||
tx_id = Some(x.parse().unwrap());
|
||||
}
|
||||
}
|
||||
if let Some(tx_slate_ids) = params.get("tx_id") {
|
||||
if let Some(x) = tx_slate_ids.first() {
|
||||
tx_slate_id = Some(x.parse().unwrap());
|
||||
}
|
||||
}
|
||||
api.retrieve_txs(update_from_node, tx_id, tx_slate_id)
|
||||
}
|
||||
|
||||
pub fn retrieve_stored_tx(
|
||||
&self,
|
||||
req: &Request<Body>,
|
||||
api: APIOwner<T, C, K>,
|
||||
) -> Result<(bool, Option<Transaction>), Error> {
|
||||
let params = parse_params(req);
|
||||
if let Some(id_string) = params.get("id") {
|
||||
match id_string[0].parse() {
|
||||
Ok(id) => match api.retrieve_txs(true, Some(id), None) {
|
||||
Ok((_, txs)) => {
|
||||
let stored_tx = api.get_stored_tx(&txs[0])?;
|
||||
Ok((txs[0].confirmed, stored_tx))
|
||||
}
|
||||
Err(e) => {
|
||||
error!("retrieve_stored_tx: failed with error: {}", e);
|
||||
Err(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("retrieve_stored_tx: could not parse id: {}", e);
|
||||
Err(ErrorKind::TransactionDumpError(
|
||||
"retrieve_stored_tx: cannot dump transaction. Could not parse id in request.",
|
||||
).into())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(ErrorKind::TransactionDumpError(
|
||||
"retrieve_stored_tx: Cannot retrieve transaction. Missing id param in request.",
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retrieve_summary_info(
|
||||
&self,
|
||||
req: &Request<Body>,
|
||||
mut api: APIOwner<T, C, K>,
|
||||
) -> Result<(bool, WalletInfo), Error> {
|
||||
let mut minimum_confirmations = 1; // TODO - default needed here
|
||||
let params = parse_params(req);
|
||||
let update_from_node = params.get("refresh").is_some();
|
||||
|
||||
if let Some(confs) = params.get("minimum_confirmations") {
|
||||
if let Some(x) = confs.first() {
|
||||
minimum_confirmations = x.parse().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
api.retrieve_summary_info(update_from_node, minimum_confirmations)
|
||||
}
|
||||
|
||||
pub fn node_height(
|
||||
&self,
|
||||
_req: &Request<Body>,
|
||||
mut api: APIOwner<T, C, K>,
|
||||
) -> Result<(u64, bool), Error> {
|
||||
api.node_height()
|
||||
}
|
||||
|
||||
fn handle_get_request(&self, req: &Request<Body>) -> Result<Response<Body>, Error> {
|
||||
let api = APIOwner::new(self.wallet.clone());
|
||||
|
||||
Ok(
|
||||
match req
|
||||
.uri()
|
||||
.path()
|
||||
.trim_right_matches("/")
|
||||
.rsplit("/")
|
||||
.next()
|
||||
.unwrap()
|
||||
{
|
||||
"retrieve_outputs" => json_response(&self.retrieve_outputs(req, api)?),
|
||||
"retrieve_summary_info" => json_response(&self.retrieve_summary_info(req, api)?),
|
||||
"node_height" => json_response(&self.node_height(req, api)?),
|
||||
"retrieve_txs" => json_response(&self.retrieve_txs(req, api)?),
|
||||
"retrieve_stored_tx" => json_response(&self.retrieve_stored_tx(req, api)?),
|
||||
_ => response(StatusCode::BAD_REQUEST, ""),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn issue_send_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
mut api: APIOwner<T, C, K>,
|
||||
) -> Box<dyn Future<Item = Slate, Error = Error> + Send> {
|
||||
Box::new(parse_body(req).and_then(move |args: SendTXArgs| {
|
||||
let result = api.initiate_tx(
|
||||
None,
|
||||
args.amount,
|
||||
args.minimum_confirmations,
|
||||
args.max_outputs,
|
||||
args.num_change_outputs,
|
||||
args.selection_strategy_is_use_all,
|
||||
args.message,
|
||||
);
|
||||
let (mut slate, lock_fn) = match result {
|
||||
Ok(s) => {
|
||||
info!(
|
||||
"Tx created: {} grin to {} (strategy '{}')",
|
||||
core::amount_to_hr_string(args.amount, false),
|
||||
&args.dest,
|
||||
args.selection_strategy_is_use_all,
|
||||
);
|
||||
s
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Tx not created: {}", e);
|
||||
match e.kind() {
|
||||
// user errors, don't backtrace
|
||||
ErrorKind::NotEnoughFunds { .. } => {}
|
||||
ErrorKind::Fee { .. } => {}
|
||||
_ => {
|
||||
// otherwise give full dump
|
||||
error!("Backtrace: {}", e.backtrace().unwrap());
|
||||
}
|
||||
};
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
match args.method.as_ref() {
|
||||
"http" => slate = HTTPWalletCommAdapter::new().send_tx_sync(&args.dest, &slate)?,
|
||||
"file" => {
|
||||
FileWalletCommAdapter::new().send_tx_async(&args.dest, &slate)?;
|
||||
}
|
||||
"keybase" => {
|
||||
//TODO: in case of keybase, the response might take 60s and leave the service hanging
|
||||
slate = KeybaseWalletCommAdapter::new().send_tx_sync(&args.dest, &slate)?;
|
||||
}
|
||||
_ => {
|
||||
error!("unsupported payment method: {}", args.method);
|
||||
return Err(ErrorKind::ClientCallback(
|
||||
"unsupported payment method".to_owned(),
|
||||
))?;
|
||||
}
|
||||
}
|
||||
api.tx_lock_outputs(&slate, lock_fn)?;
|
||||
if args.method != "file" {
|
||||
api.finalize_tx(&mut slate)?;
|
||||
}
|
||||
Ok(slate)
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn finalize_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
mut api: APIOwner<T, C, K>,
|
||||
) -> Box<dyn Future<Item = Slate, Error = Error> + Send> {
|
||||
Box::new(
|
||||
parse_body(req).and_then(move |mut slate| match api.finalize_tx(&mut slate) {
|
||||
Ok(_) => ok(slate.clone()),
|
||||
Err(e) => {
|
||||
error!("finalize_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn cancel_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
mut api: APIOwner<T, C, K>,
|
||||
) -> Box<dyn Future<Item = (), Error = Error> + Send> {
|
||||
let params = parse_params(&req);
|
||||
if let Some(id_string) = params.get("id") {
|
||||
Box::new(match id_string[0].parse() {
|
||||
Ok(id) => match api.cancel_tx(Some(id), None) {
|
||||
Ok(_) => ok(()),
|
||||
Err(e) => {
|
||||
error!("cancel_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("cancel_tx: could not parse id: {}", e);
|
||||
err(ErrorKind::TransactionCancellationError(
|
||||
"cancel_tx: cannot cancel transaction. Could not parse id in request.",
|
||||
)
|
||||
.into())
|
||||
}
|
||||
})
|
||||
} else if let Some(tx_id_string) = params.get("tx_id") {
|
||||
Box::new(match tx_id_string[0].parse() {
|
||||
Ok(tx_id) => match api.cancel_tx(None, Some(tx_id)) {
|
||||
Ok(_) => ok(()),
|
||||
Err(e) => {
|
||||
error!("cancel_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("cancel_tx: could not parse tx_id: {}", e);
|
||||
err(ErrorKind::TransactionCancellationError(
|
||||
"cancel_tx: cannot cancel transaction. Could not parse tx_id in request.",
|
||||
)
|
||||
.into())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Box::new(err(ErrorKind::TransactionCancellationError(
|
||||
"cancel_tx: Cannot cancel transaction. Missing id or tx_id param in request.",
|
||||
)
|
||||
.into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
api: APIOwner<T, C, K>,
|
||||
) -> Box<dyn Future<Item = (), Error = Error> + Send> {
|
||||
let params = match req.uri().query() {
|
||||
Some(query_string) => form_urlencoded::parse(query_string.as_bytes())
|
||||
.into_owned()
|
||||
.fold(HashMap::new(), |mut hm, (k, v)| {
|
||||
hm.entry(k).or_insert(vec![]).push(v);
|
||||
hm
|
||||
}),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let fluff = params.get("fluff").is_some();
|
||||
Box::new(parse_body(req).and_then(
|
||||
move |slate: Slate| match api.post_tx(&slate.tx, fluff) {
|
||||
Ok(_) => ok(()),
|
||||
Err(e) => {
|
||||
error!("post_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn repost(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
api: APIOwner<T, C, K>,
|
||||
) -> Box<dyn Future<Item = (), Error = Error> + Send> {
|
||||
let params = parse_params(&req);
|
||||
let mut id_int: Option<u32> = None;
|
||||
let mut tx_uuid: Option<Uuid> = None;
|
||||
|
||||
if let Some(id_string) = params.get("id") {
|
||||
match id_string[0].parse() {
|
||||
Ok(id) => id_int = Some(id),
|
||||
Err(e) => {
|
||||
error!("repost: could not parse id: {}", e);
|
||||
return Box::new(err(ErrorKind::GenericError(
|
||||
"repost: cannot repost transaction. Could not parse id in request."
|
||||
.to_owned(),
|
||||
)
|
||||
.into()));
|
||||
}
|
||||
}
|
||||
} else if let Some(tx_id_string) = params.get("tx_id") {
|
||||
match tx_id_string[0].parse() {
|
||||
Ok(tx_id) => tx_uuid = Some(tx_id),
|
||||
Err(e) => {
|
||||
error!("repost: could not parse tx_id: {}", e);
|
||||
return Box::new(err(ErrorKind::GenericError(
|
||||
"repost: cannot repost transaction. Could not parse tx_id in request."
|
||||
.to_owned(),
|
||||
)
|
||||
.into()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Box::new(err(ErrorKind::GenericError(
|
||||
"repost: Cannot repost transaction. Missing id or tx_id param in request."
|
||||
.to_owned(),
|
||||
)
|
||||
.into()));
|
||||
}
|
||||
|
||||
let res = api.retrieve_txs(true, id_int, tx_uuid);
|
||||
if let Err(e) = res {
|
||||
return Box::new(err(ErrorKind::GenericError(format!(
|
||||
"repost: cannot repost transaction. retrieve_txs failed, err: {:?}",
|
||||
e
|
||||
))
|
||||
.into()));
|
||||
}
|
||||
let (_, txs) = res.unwrap();
|
||||
let res = api.get_stored_tx(&txs[0]);
|
||||
if let Err(e) = res {
|
||||
return Box::new(err(ErrorKind::GenericError(format!(
|
||||
"repost: cannot repost transaction. get_stored_tx failed, err: {:?}",
|
||||
e
|
||||
))
|
||||
.into()));
|
||||
}
|
||||
let stored_tx = res.unwrap();
|
||||
if stored_tx.is_none() {
|
||||
error!(
|
||||
"Transaction with id {:?}/{:?} does not have transaction data. Not reposting.",
|
||||
id_int, tx_uuid,
|
||||
);
|
||||
return Box::new(err(ErrorKind::GenericError(
|
||||
"repost: Cannot repost transaction. Missing id or tx_id param in request."
|
||||
.to_owned(),
|
||||
)
|
||||
.into()));
|
||||
}
|
||||
|
||||
let fluff = params.get("fluff").is_some();
|
||||
Box::new(match api.post_tx(&stored_tx.unwrap(), fluff) {
|
||||
Ok(_) => ok(()),
|
||||
Err(e) => {
|
||||
error!("repost: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_post_request(&self, req: Request<Body>) -> WalletResponseFuture {
|
||||
let api = APIOwner::new(self.wallet.clone());
|
||||
match req
|
||||
.uri()
|
||||
.path()
|
||||
.trim_right_matches("/")
|
||||
.rsplit("/")
|
||||
.next()
|
||||
.unwrap()
|
||||
{
|
||||
"issue_send_tx" => Box::new(
|
||||
self.issue_send_tx(req, api)
|
||||
.and_then(|slate| ok(json_response_pretty(&slate))),
|
||||
),
|
||||
"finalize_tx" => Box::new(
|
||||
self.finalize_tx(req, api)
|
||||
.and_then(|slate| ok(json_response_pretty(&slate))),
|
||||
),
|
||||
"cancel_tx" => Box::new(
|
||||
self.cancel_tx(req, api)
|
||||
.and_then(|_| ok(response(StatusCode::OK, "{}"))),
|
||||
),
|
||||
"post_tx" => Box::new(
|
||||
self.post_tx(req, api)
|
||||
.and_then(|_| ok(response(StatusCode::OK, "{}"))),
|
||||
),
|
||||
"repost" => Box::new(
|
||||
self.repost(req, api)
|
||||
.and_then(|_| ok(response(StatusCode::OK, ""))),
|
||||
),
|
||||
_ => Box::new(err(ErrorKind::GenericError(
|
||||
"Unknown error handling post request".to_owned(),
|
||||
)
|
||||
.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized, C, K> Handler for OwnerAPIHandler<T, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
fn get(&self, req: Request<Body>) -> ResponseFuture {
|
||||
match self.handle_get_request(&req) {
|
||||
Ok(r) => Box::new(ok(r)),
|
||||
Err(e) => {
|
||||
error!("Request Error: {:?}", e);
|
||||
Box::new(ok(create_error_response(e)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn post(&self, req: Request<Body>) -> ResponseFuture {
|
||||
Box::new(
|
||||
self.handle_post_request(req)
|
||||
.and_then(|r| ok(r))
|
||||
.or_else(|e| {
|
||||
error!("Request Error: {:?}", e);
|
||||
ok(create_error_response(e))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn options(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
Box::new(ok(create_ok_response("{}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// API Handler/Wrapper for foreign functions
|
||||
|
||||
pub struct ForeignAPIHandler<T: ?Sized, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
/// Wallet instance
|
||||
pub wallet: Arc<Mutex<T>>,
|
||||
phantom: PhantomData<K>,
|
||||
phantom_c: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T: ?Sized, C, K> ForeignAPIHandler<T, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
/// create a new api handler
|
||||
pub fn new(wallet: Arc<Mutex<T>>) -> ForeignAPIHandler<T, C, K> {
|
||||
ForeignAPIHandler {
|
||||
wallet,
|
||||
phantom: PhantomData,
|
||||
phantom_c: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_coinbase(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
mut api: APIForeign<T, C, K>,
|
||||
) -> Box<dyn Future<Item = CbData, Error = Error> + Send> {
|
||||
Box::new(parse_body(req).and_then(move |block_fees| api.build_coinbase(&block_fees)))
|
||||
}
|
||||
|
||||
fn receive_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
mut api: APIForeign<T, C, K>,
|
||||
) -> Box<dyn Future<Item = VersionedSlate, Error = Error> + Send> {
|
||||
Box::new(parse_body(req).and_then(
|
||||
//TODO: No way to insert a message from the params
|
||||
move |slate: VersionedSlate| {
|
||||
let mut slate: Slate = slate.into();
|
||||
if let Err(e) = api.verify_slate_messages(&slate) {
|
||||
error!("Error validating participant messages: {}", e);
|
||||
err(e)
|
||||
} else {
|
||||
match api.receive_tx(&mut slate, None, None) {
|
||||
Ok(_) => ok(get_versioned_slate(&slate.clone())),
|
||||
Err(e) => {
|
||||
error!("receive_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn handle_request(&self, req: Request<Body>) -> WalletResponseFuture {
|
||||
let api = *APIForeign::new(self.wallet.clone());
|
||||
match req
|
||||
.uri()
|
||||
.path()
|
||||
.trim_right_matches("/")
|
||||
.rsplit("/")
|
||||
.next()
|
||||
.unwrap()
|
||||
{
|
||||
"build_coinbase" => Box::new(
|
||||
self.build_coinbase(req, api)
|
||||
.and_then(|res| ok(json_response(&res))),
|
||||
),
|
||||
"receive_tx" => Box::new(
|
||||
self.receive_tx(req, api)
|
||||
.and_then(|res| ok(json_response(&res))),
|
||||
),
|
||||
_ => Box::new(ok(response(StatusCode::BAD_REQUEST, "unknown action"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T: ?Sized, C, K> Handler for ForeignAPIHandler<T, C, K>
|
||||
where
|
||||
T: WalletBackend<C, K> + Send + Sync + 'static,
|
||||
C: NodeClient + Send + Sync + 'static,
|
||||
K: Keychain + 'static,
|
||||
{
|
||||
fn post(&self, req: Request<Body>) -> ResponseFuture {
|
||||
Box::new(self.handle_request(req).and_then(|r| ok(r)).or_else(|e| {
|
||||
error!("Request Error: {:?}", e);
|
||||
ok(create_error_response(e))
|
||||
}))
|
||||
}
|
||||
|
||||
fn options(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
Box::new(ok(create_ok_response("{}")))
|
||||
}
|
||||
}
|
||||
|
||||
// Utility to serialize a struct into JSON and produce a sensible Response
|
||||
// out of it.
|
||||
fn json_response<T>(s: &T) -> Response<Body>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
match serde_json::to_string(s) {
|
||||
Ok(json) => response(StatusCode::OK, json),
|
||||
Err(_) => response(StatusCode::INTERNAL_SERVER_ERROR, ""),
|
||||
}
|
||||
}
|
||||
|
||||
// pretty-printed version of above
|
||||
fn json_response_pretty<T>(s: &T) -> Response<Body>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
match serde_json::to_string_pretty(s) {
|
||||
Ok(json) => response(StatusCode::OK, json),
|
||||
Err(_) => response(StatusCode::INTERNAL_SERVER_ERROR, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_error_response(e: Error) -> Response<Body> {
|
||||
Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.header("access-control-allow-origin", "*")
|
||||
.header(
|
||||
"access-control-allow-headers",
|
||||
"Content-Type, Authorization",
|
||||
)
|
||||
.body(format!("{}", e).into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn create_ok_response(json: &str) -> Response<Body> {
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("access-control-allow-origin", "*")
|
||||
.header(
|
||||
"access-control-allow-headers",
|
||||
"Content-Type, Authorization",
|
||||
)
|
||||
.header(hyper::header::CONTENT_TYPE, "application/json")
|
||||
.body(json.to_string().into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Build a new hyper Response with the status code and body provided.
|
||||
///
|
||||
/// Whenever the status code is `StatusCode::OK` the text parameter should be
|
||||
/// valid JSON as the content type header will be set to `application/json'
|
||||
fn response<T: Into<Body>>(status: StatusCode, text: T) -> Response<Body> {
|
||||
let mut builder = &mut Response::builder();
|
||||
|
||||
builder = builder
|
||||
.status(status)
|
||||
.header("access-control-allow-origin", "*")
|
||||
.header(
|
||||
"access-control-allow-headers",
|
||||
"Content-Type, Authorization",
|
||||
);
|
||||
|
||||
if status == StatusCode::OK {
|
||||
builder = builder.header(hyper::header::CONTENT_TYPE, "application/json");
|
||||
}
|
||||
|
||||
builder.body(text.into()).unwrap()
|
||||
}
|
||||
|
||||
fn parse_params(req: &Request<Body>) -> HashMap<String, Vec<String>> {
|
||||
match req.uri().query() {
|
||||
Some(query_string) => form_urlencoded::parse(query_string.as_bytes())
|
||||
.into_owned()
|
||||
.fold(HashMap::new(), |mut hm, (k, v)| {
|
||||
hm.entry(k).or_insert(vec![]).push(v);
|
||||
hm
|
||||
}),
|
||||
None => HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_body<T>(req: Request<Body>) -> Box<dyn Future<Item = T, Error = Error> + Send>
|
||||
where
|
||||
for<'de> T: Deserialize<'de> + Send + 'static,
|
||||
{
|
||||
Box::new(
|
||||
req.into_body()
|
||||
.concat2()
|
||||
.map_err(|_| ErrorKind::GenericError("Failed to read request".to_owned()).into())
|
||||
.and_then(|body| match serde_json::from_reader(&body.to_vec()[..]) {
|
||||
Ok(obj) => ok(obj),
|
||||
Err(e) => {
|
||||
err(ErrorKind::GenericError(format!("Invalid request body: {}", e)).into())
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
// 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 crate::core::core::{self, amount_to_hr_string};
|
||||
use crate::core::global;
|
||||
use crate::libwallet::types::{AcctPathMapping, OutputData, OutputStatus, TxLogEntry, WalletInfo};
|
||||
use crate::libwallet::Error;
|
||||
use crate::util;
|
||||
use crate::util::secp::pedersen;
|
||||
use prettytable;
|
||||
use std::io::prelude::Write;
|
||||
use term;
|
||||
|
||||
/// Display outputs in a pretty way
|
||||
pub fn outputs(
|
||||
account: &str,
|
||||
cur_height: u64,
|
||||
validated: bool,
|
||||
outputs: Vec<(OutputData, pedersen::Commitment)>,
|
||||
dark_background_color_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
let title = format!(
|
||||
"Wallet Outputs - Account '{}' - Block Height: {}",
|
||||
account, cur_height
|
||||
);
|
||||
println!();
|
||||
let mut t = term::stdout().unwrap();
|
||||
t.fg(term::color::MAGENTA).unwrap();
|
||||
writeln!(t, "{}", title).unwrap();
|
||||
t.reset().unwrap();
|
||||
|
||||
let mut table = table!();
|
||||
|
||||
table.set_titles(row![
|
||||
bMG->"Output Commitment",
|
||||
bMG->"MMR Index",
|
||||
bMG->"Block Height",
|
||||
bMG->"Locked Until",
|
||||
bMG->"Status",
|
||||
bMG->"Coinbase?",
|
||||
bMG->"# Confirms",
|
||||
bMG->"Value",
|
||||
bMG->"Tx"
|
||||
]);
|
||||
|
||||
for (out, commit) in outputs {
|
||||
let commit = format!("{}", util::to_hex(commit.as_ref().to_vec()));
|
||||
let index = match out.mmr_index {
|
||||
None => "None".to_owned(),
|
||||
Some(t) => t.to_string(),
|
||||
};
|
||||
let height = format!("{}", out.height);
|
||||
let lock_height = format!("{}", out.lock_height);
|
||||
let is_coinbase = format!("{}", out.is_coinbase);
|
||||
|
||||
// Mark unconfirmed coinbase outputs as "Mining" instead of "Unconfirmed"
|
||||
let status = match out.status {
|
||||
OutputStatus::Unconfirmed if out.is_coinbase => "Mining".to_string(),
|
||||
_ => format!("{}", out.status),
|
||||
};
|
||||
|
||||
let num_confirmations = format!("{}", out.num_confirmations(cur_height));
|
||||
let value = format!("{}", core::amount_to_hr_string(out.value, false));
|
||||
let tx = match out.tx_log_entry {
|
||||
None => "".to_owned(),
|
||||
Some(t) => t.to_string(),
|
||||
};
|
||||
|
||||
if dark_background_color_scheme {
|
||||
table.add_row(row![
|
||||
bFC->commit,
|
||||
bFB->index,
|
||||
bFB->height,
|
||||
bFB->lock_height,
|
||||
bFR->status,
|
||||
bFY->is_coinbase,
|
||||
bFB->num_confirmations,
|
||||
bFG->value,
|
||||
bFC->tx,
|
||||
]);
|
||||
} else {
|
||||
table.add_row(row![
|
||||
bFD->commit,
|
||||
bFB->index,
|
||||
bFB->height,
|
||||
bFB->lock_height,
|
||||
bFR->status,
|
||||
bFD->is_coinbase,
|
||||
bFB->num_confirmations,
|
||||
bFG->value,
|
||||
bFD->tx,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP);
|
||||
table.printstd();
|
||||
println!();
|
||||
|
||||
if !validated {
|
||||
println!(
|
||||
"\nWARNING: Wallet failed to verify data. \
|
||||
The above is from local cache and possibly invalid! \
|
||||
(is your `grin server` offline or broken?)"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Display transaction log in a pretty way
|
||||
pub fn txs(
|
||||
account: &str,
|
||||
cur_height: u64,
|
||||
validated: bool,
|
||||
txs: &Vec<TxLogEntry>,
|
||||
include_status: bool,
|
||||
dark_background_color_scheme: bool,
|
||||
) -> Result<(), Error> {
|
||||
let title = format!(
|
||||
"Transaction Log - Account '{}' - Block Height: {}",
|
||||
account, cur_height
|
||||
);
|
||||
println!();
|
||||
let mut t = term::stdout().unwrap();
|
||||
t.fg(term::color::MAGENTA).unwrap();
|
||||
writeln!(t, "{}", title).unwrap();
|
||||
t.reset().unwrap();
|
||||
|
||||
let mut table = table!();
|
||||
|
||||
table.set_titles(row![
|
||||
bMG->"Id",
|
||||
bMG->"Type",
|
||||
bMG->"Shared Transaction Id",
|
||||
bMG->"Creation Time",
|
||||
bMG->"Confirmed?",
|
||||
bMG->"Confirmation Time",
|
||||
bMG->"Num. \nInputs",
|
||||
bMG->"Num. \nOutputs",
|
||||
bMG->"Amount \nCredited",
|
||||
bMG->"Amount \nDebited",
|
||||
bMG->"Fee",
|
||||
bMG->"Net \nDifference",
|
||||
bMG->"Tx \nData",
|
||||
]);
|
||||
|
||||
for t in txs {
|
||||
let id = format!("{}", t.id);
|
||||
let slate_id = match t.tx_slate_id {
|
||||
Some(m) => format!("{}", m),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
let entry_type = format!("{}", t.tx_type);
|
||||
let creation_ts = format!("{}", t.creation_ts.format("%Y-%m-%d %H:%M:%S"));
|
||||
let confirmation_ts = match t.confirmation_ts {
|
||||
Some(m) => format!("{}", m.format("%Y-%m-%d %H:%M:%S")),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
let confirmed = format!("{}", t.confirmed);
|
||||
let num_inputs = format!("{}", t.num_inputs);
|
||||
let num_outputs = format!("{}", t.num_outputs);
|
||||
let amount_debited_str = core::amount_to_hr_string(t.amount_debited, true);
|
||||
let amount_credited_str = core::amount_to_hr_string(t.amount_credited, true);
|
||||
let fee = match t.fee {
|
||||
Some(f) => format!("{}", core::amount_to_hr_string(f, true)),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
let net_diff = if t.amount_credited >= t.amount_debited {
|
||||
core::amount_to_hr_string(t.amount_credited - t.amount_debited, true)
|
||||
} else {
|
||||
format!(
|
||||
"-{}",
|
||||
core::amount_to_hr_string(t.amount_debited - t.amount_credited, true)
|
||||
)
|
||||
};
|
||||
let tx_data = match t.stored_tx {
|
||||
Some(_) => "Yes".to_owned(),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
if dark_background_color_scheme {
|
||||
table.add_row(row![
|
||||
bFC->id,
|
||||
bFC->entry_type,
|
||||
bFC->slate_id,
|
||||
bFB->creation_ts,
|
||||
bFC->confirmed,
|
||||
bFB->confirmation_ts,
|
||||
bFC->num_inputs,
|
||||
bFC->num_outputs,
|
||||
bFG->amount_credited_str,
|
||||
bFR->amount_debited_str,
|
||||
bFR->fee,
|
||||
bFY->net_diff,
|
||||
bFb->tx_data,
|
||||
]);
|
||||
} else {
|
||||
if t.confirmed {
|
||||
table.add_row(row![
|
||||
bFD->id,
|
||||
bFb->entry_type,
|
||||
bFD->slate_id,
|
||||
bFB->creation_ts,
|
||||
bFg->confirmed,
|
||||
bFB->confirmation_ts,
|
||||
bFD->num_inputs,
|
||||
bFD->num_outputs,
|
||||
bFG->amount_credited_str,
|
||||
bFD->amount_debited_str,
|
||||
bFD->fee,
|
||||
bFG->net_diff,
|
||||
bFB->tx_data,
|
||||
]);
|
||||
} else {
|
||||
table.add_row(row![
|
||||
bFD->id,
|
||||
bFb->entry_type,
|
||||
bFD->slate_id,
|
||||
bFB->creation_ts,
|
||||
bFR->confirmed,
|
||||
bFB->confirmation_ts,
|
||||
bFD->num_inputs,
|
||||
bFD->num_outputs,
|
||||
bFG->amount_credited_str,
|
||||
bFD->amount_debited_str,
|
||||
bFD->fee,
|
||||
bFG->net_diff,
|
||||
bFB->tx_data,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP);
|
||||
table.printstd();
|
||||
println!();
|
||||
|
||||
if !validated && include_status {
|
||||
println!(
|
||||
"\nWARNING: Wallet failed to verify data. \
|
||||
The above is from local cache and possibly invalid! \
|
||||
(is your `grin server` offline or broken?)"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Display summary info in a pretty way
|
||||
pub fn info(
|
||||
account: &str,
|
||||
wallet_info: &WalletInfo,
|
||||
validated: bool,
|
||||
dark_background_color_scheme: bool,
|
||||
) {
|
||||
println!(
|
||||
"\n____ Wallet Summary Info - Account '{}' as of height {} ____\n",
|
||||
account, wallet_info.last_confirmed_height,
|
||||
);
|
||||
|
||||
let mut table = table!();
|
||||
|
||||
if dark_background_color_scheme {
|
||||
table.add_row(row![
|
||||
bFG->"Total",
|
||||
FG->amount_to_hr_string(wallet_info.total, false)
|
||||
]);
|
||||
// Only dispay "Immature Coinbase" if we have related outputs in the wallet.
|
||||
// This row just introduces confusion if the wallet does not receive coinbase rewards.
|
||||
if wallet_info.amount_immature > 0 {
|
||||
table.add_row(row![
|
||||
bFY->format!("Immature Coinbase (< {})", global::coinbase_maturity()),
|
||||
FY->amount_to_hr_string(wallet_info.amount_immature, false)
|
||||
]);
|
||||
}
|
||||
table.add_row(row![
|
||||
bFY->format!("Awaiting Confirmation (< {})", wallet_info.minimum_confirmations),
|
||||
FY->amount_to_hr_string(wallet_info.amount_awaiting_confirmation, false)
|
||||
]);
|
||||
table.add_row(row![
|
||||
Fr->"Locked by previous transaction",
|
||||
Fr->amount_to_hr_string(wallet_info.amount_locked, false)
|
||||
]);
|
||||
table.add_row(row![
|
||||
Fw->"--------------------------------",
|
||||
Fw->"-------------"
|
||||
]);
|
||||
table.add_row(row![
|
||||
bFG->"Currently Spendable",
|
||||
FG->amount_to_hr_string(wallet_info.amount_currently_spendable, false)
|
||||
]);
|
||||
} else {
|
||||
table.add_row(row![
|
||||
bFG->"Total",
|
||||
FG->amount_to_hr_string(wallet_info.total, false)
|
||||
]);
|
||||
// Only dispay "Immature Coinbase" if we have related outputs in the wallet.
|
||||
// This row just introduces confusion if the wallet does not receive coinbase rewards.
|
||||
if wallet_info.amount_immature > 0 {
|
||||
table.add_row(row![
|
||||
bFB->format!("Immature Coinbase (< {})", global::coinbase_maturity()),
|
||||
FB->amount_to_hr_string(wallet_info.amount_immature, false)
|
||||
]);
|
||||
}
|
||||
table.add_row(row![
|
||||
bFB->format!("Awaiting Confirmation (< {})", wallet_info.minimum_confirmations),
|
||||
FB->amount_to_hr_string(wallet_info.amount_awaiting_confirmation, false)
|
||||
]);
|
||||
table.add_row(row![
|
||||
Fr->"Locked by previous transaction",
|
||||
Fr->amount_to_hr_string(wallet_info.amount_locked, false)
|
||||
]);
|
||||
table.add_row(row![
|
||||
Fw->"--------------------------------",
|
||||
Fw->"-------------"
|
||||
]);
|
||||
table.add_row(row![
|
||||
bFG->"Currently Spendable",
|
||||
FG->amount_to_hr_string(wallet_info.amount_currently_spendable, false)
|
||||
]);
|
||||
};
|
||||
table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
|
||||
table.printstd();
|
||||
println!();
|
||||
if !validated {
|
||||
println!(
|
||||
"\nWARNING: Wallet failed to verify data against a live chain. \
|
||||
The above is from local cache and only valid up to the given height! \
|
||||
(is your `grin server` offline or broken?)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Display summary info in a pretty way
|
||||
pub fn estimate(
|
||||
amount: u64,
|
||||
strategies: Vec<(
|
||||
&str, // strategy
|
||||
u64, // total amount to be locked
|
||||
u64, // fee
|
||||
)>,
|
||||
dark_background_color_scheme: bool,
|
||||
) {
|
||||
println!(
|
||||
"\nEstimation for sending {}:\n",
|
||||
amount_to_hr_string(amount, false)
|
||||
);
|
||||
|
||||
let mut table = table!();
|
||||
|
||||
table.set_titles(row![
|
||||
bMG->"Selection strategy",
|
||||
bMG->"Fee",
|
||||
bMG->"Will be locked",
|
||||
]);
|
||||
|
||||
for (strategy, total, fee) in strategies {
|
||||
if dark_background_color_scheme {
|
||||
table.add_row(row![
|
||||
bFC->strategy,
|
||||
FR->amount_to_hr_string(fee, false),
|
||||
FY->amount_to_hr_string(total, false),
|
||||
]);
|
||||
} else {
|
||||
table.add_row(row![
|
||||
bFD->strategy,
|
||||
FR->amount_to_hr_string(fee, false),
|
||||
FY->amount_to_hr_string(total, false),
|
||||
]);
|
||||
}
|
||||
}
|
||||
table.printstd();
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Display list of wallet accounts in a pretty way
|
||||
pub fn accounts(acct_mappings: Vec<AcctPathMapping>) {
|
||||
println!("\n____ Wallet Accounts ____\n",);
|
||||
let mut table = table!();
|
||||
|
||||
table.set_titles(row![
|
||||
mMG->"Name",
|
||||
bMG->"Parent BIP-32 Derivation Path",
|
||||
]);
|
||||
for m in acct_mappings {
|
||||
table.add_row(row![
|
||||
bFC->m.label,
|
||||
bGC->m.path.to_bip_32_string(),
|
||||
]);
|
||||
}
|
||||
table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
|
||||
table.printstd();
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Display transaction log messages
|
||||
pub fn tx_messages(tx: &TxLogEntry, dark_background_color_scheme: bool) -> Result<(), Error> {
|
||||
let title = format!("Transaction Messages - Transaction '{}'", tx.id,);
|
||||
println!();
|
||||
let mut t = term::stdout().unwrap();
|
||||
t.fg(term::color::MAGENTA).unwrap();
|
||||
writeln!(t, "{}", title).unwrap();
|
||||
t.reset().unwrap();
|
||||
|
||||
let msgs = match tx.messages.clone() {
|
||||
None => {
|
||||
writeln!(t, "{}", "None").unwrap();
|
||||
t.reset().unwrap();
|
||||
return Ok(());
|
||||
}
|
||||
Some(m) => m.clone(),
|
||||
};
|
||||
|
||||
if msgs.messages.is_empty() {
|
||||
writeln!(t, "{}", "None").unwrap();
|
||||
t.reset().unwrap();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut table = table!();
|
||||
|
||||
table.set_titles(row![
|
||||
bMG->"Participant Id",
|
||||
bMG->"Message",
|
||||
bMG->"Public Key",
|
||||
bMG->"Signature",
|
||||
]);
|
||||
|
||||
let secp = util::static_secp_instance();
|
||||
let secp_lock = secp.lock();
|
||||
|
||||
for m in msgs.messages {
|
||||
let id = format!("{}", m.id);
|
||||
let public_key = format!(
|
||||
"{}",
|
||||
util::to_hex(m.public_key.serialize_vec(&secp_lock, true).to_vec())
|
||||
);
|
||||
let message = match m.message {
|
||||
Some(m) => format!("{}", m),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
let message_sig = match m.message_sig {
|
||||
Some(s) => format!("{}", util::to_hex(s.serialize_der(&secp_lock))),
|
||||
None => "None".to_owned(),
|
||||
};
|
||||
if dark_background_color_scheme {
|
||||
table.add_row(row![
|
||||
bFC->id,
|
||||
bFC->message,
|
||||
bFC->public_key,
|
||||
bFB->message_sig,
|
||||
]);
|
||||
} else {
|
||||
table.add_row(row![
|
||||
bFD->id,
|
||||
bFb->message,
|
||||
bFD->public_key,
|
||||
bFB->message_sig,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP);
|
||||
table.printstd();
|
||||
println!();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// 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.
|
||||
|
||||
//! Implementation specific error types
|
||||
use crate::api;
|
||||
use crate::core::core::transaction;
|
||||
use crate::core::libtx;
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use failure::{Backtrace, Context, Fail};
|
||||
use std::env;
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
/// Error definition
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
pub inner: Context<ErrorKind>,
|
||||
}
|
||||
|
||||
/// Wallet errors, mostly wrappers around underlying crypto or I/O errors.
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
|
||||
pub enum ErrorKind {
|
||||
/// LibTX Error
|
||||
#[fail(display = "LibTx Error")]
|
||||
LibTX(libtx::ErrorKind),
|
||||
|
||||
/// LibWallet Error
|
||||
#[fail(display = "LibWallet Error: {}", _1)]
|
||||
LibWallet(libwallet::ErrorKind, String),
|
||||
|
||||
/// Keychain error
|
||||
#[fail(display = "Keychain error")]
|
||||
Keychain(keychain::Error),
|
||||
|
||||
/// Transaction Error
|
||||
#[fail(display = "Transaction error")]
|
||||
Transaction(transaction::Error),
|
||||
|
||||
/// Secp Error
|
||||
#[fail(display = "Secp error")]
|
||||
Secp,
|
||||
|
||||
/// Filewallet error
|
||||
#[fail(display = "Wallet data error: {}", _0)]
|
||||
FileWallet(&'static str),
|
||||
|
||||
/// Error when formatting json
|
||||
#[fail(display = "IO error")]
|
||||
IO,
|
||||
|
||||
/// Error when formatting json
|
||||
#[fail(display = "Serde JSON error")]
|
||||
Format,
|
||||
|
||||
/// Error when contacting a node through its API
|
||||
#[fail(display = "Node API error")]
|
||||
Node(api::ErrorKind),
|
||||
|
||||
/// Error originating from hyper.
|
||||
#[fail(display = "Hyper error")]
|
||||
Hyper,
|
||||
|
||||
/// Error originating from hyper uri parsing.
|
||||
#[fail(display = "Uri parsing error")]
|
||||
Uri,
|
||||
|
||||
/// Attempt to use duplicate transaction id in separate transactions
|
||||
#[fail(display = "Duplicate transaction ID error")]
|
||||
DuplicateTransactionId,
|
||||
|
||||
/// Wallet seed already exists
|
||||
#[fail(display = "Wallet seed file exists: {}", _0)]
|
||||
WalletSeedExists(String),
|
||||
|
||||
/// Wallet seed doesn't exist
|
||||
#[fail(display = "Wallet seed doesn't exist error")]
|
||||
WalletSeedDoesntExist,
|
||||
|
||||
/// Enc/Decryption Error
|
||||
#[fail(display = "Enc/Decryption error (check password?)")]
|
||||
Encryption,
|
||||
|
||||
/// BIP 39 word list
|
||||
#[fail(display = "BIP39 Mnemonic (word list) Error")]
|
||||
Mnemonic,
|
||||
|
||||
/// Command line argument error
|
||||
#[fail(display = "{}", _0)]
|
||||
ArgumentError(String),
|
||||
|
||||
/// Other
|
||||
#[fail(display = "Generic error: {}", _0)]
|
||||
GenericError(String),
|
||||
}
|
||||
|
||||
impl Fail for Error {
|
||||
fn cause(&self) -> Option<&dyn Fail> {
|
||||
self.inner.cause()
|
||||
}
|
||||
|
||||
fn backtrace(&self) -> Option<&Backtrace> {
|
||||
self.inner.backtrace()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let show_bt = match env::var("RUST_BACKTRACE") {
|
||||
Ok(r) => {
|
||||
if r == "1" {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
let backtrace = match self.backtrace() {
|
||||
Some(b) => format!("{}", b),
|
||||
None => String::from("Unknown"),
|
||||
};
|
||||
let inner_output = format!("{}", self.inner,);
|
||||
let backtrace_output = format!("\nBacktrace: {}", backtrace);
|
||||
let mut output = inner_output.clone();
|
||||
if show_bt {
|
||||
output.push_str(&backtrace_output);
|
||||
}
|
||||
Display::fmt(&output, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// get kind
|
||||
pub fn kind(&self) -> ErrorKind {
|
||||
self.inner.get_context().clone()
|
||||
}
|
||||
/// get cause
|
||||
pub fn cause(&self) -> Option<&dyn Fail> {
|
||||
self.inner.cause()
|
||||
}
|
||||
/// get backtrace
|
||||
pub fn backtrace(&self) -> Option<&Backtrace> {
|
||||
self.inner.backtrace()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ErrorKind> for Error {
|
||||
fn from(kind: ErrorKind) -> Error {
|
||||
Error {
|
||||
inner: Context::new(kind),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Context<ErrorKind>> for Error {
|
||||
fn from(inner: Context<ErrorKind>) -> Error {
|
||||
Error { inner: inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<api::Error> for Error {
|
||||
fn from(error: api::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::Node(error.kind().clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<keychain::Error> for Error {
|
||||
fn from(error: keychain::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::Keychain(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<transaction::Error> for Error {
|
||||
fn from(error: transaction::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::Transaction(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<libwallet::Error> for Error {
|
||||
fn from(error: libwallet::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::LibWallet(error.kind(), format!("{}", error))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<libtx::Error> for Error {
|
||||
fn from(error: libtx::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::LibTX(error.kind())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// 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.
|
||||
|
||||
//! Library module for the main wallet functionalities provided by Grin.
|
||||
|
||||
use blake2_rfc as blake2;
|
||||
|
||||
#[macro_use]
|
||||
extern crate prettytable;
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
use failure;
|
||||
use grin_api as api;
|
||||
#[macro_use]
|
||||
extern crate grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_store as store;
|
||||
use grin_util as util;
|
||||
|
||||
mod adapters;
|
||||
pub mod command;
|
||||
pub mod controller;
|
||||
pub mod display;
|
||||
mod error;
|
||||
pub mod libwallet;
|
||||
pub mod lmdb_wallet;
|
||||
mod node_clients;
|
||||
pub mod test_framework;
|
||||
mod types;
|
||||
|
||||
pub use crate::adapters::{
|
||||
FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter, NullWalletCommAdapter,
|
||||
WalletCommAdapter,
|
||||
};
|
||||
pub use crate::error::{Error, ErrorKind};
|
||||
pub use crate::libwallet::slate::Slate;
|
||||
pub use crate::libwallet::types::{
|
||||
BlockFees, CbData, NodeClient, WalletBackend, WalletInfo, WalletInst,
|
||||
};
|
||||
pub use crate::lmdb_wallet::{wallet_db_exists, LMDBBackend};
|
||||
pub use crate::node_clients::{create_coinbase, HTTPNodeClient};
|
||||
pub use crate::types::{EncryptedWalletSeed, WalletConfig, WalletSeed, SEED_FILE};
|
||||
|
||||
use crate::util::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Helper to create an instance of the LMDB wallet
|
||||
pub fn instantiate_wallet(
|
||||
wallet_config: WalletConfig,
|
||||
node_client: impl NodeClient + 'static,
|
||||
passphrase: &str,
|
||||
account: &str,
|
||||
) -> Result<Arc<Mutex<WalletInst<impl NodeClient, keychain::ExtKeychain>>>, Error> {
|
||||
// First test decryption, so we can abort early if we have the wrong password
|
||||
let _ = WalletSeed::from_file(&wallet_config, passphrase)?;
|
||||
let mut db_wallet = LMDBBackend::new(wallet_config.clone(), passphrase, node_client)?;
|
||||
db_wallet.set_parent_key_id_by_name(account)?;
|
||||
info!("Using LMDB Backend for wallet");
|
||||
Ok(Arc::new(Mutex::new(db_wallet)))
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
// 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::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
use std::{fs, path};
|
||||
|
||||
// for writing storedtransaction files
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use failure::ResultExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::blake2::blake2b::Blake2b;
|
||||
|
||||
use crate::keychain::{ChildNumber, ExtKeychain, Identifier, Keychain};
|
||||
use crate::store::{self, option_to_not_found, to_key, to_key_u64};
|
||||
|
||||
use crate::core::core::Transaction;
|
||||
use crate::core::{global, ser};
|
||||
use crate::libwallet::types::*;
|
||||
use crate::libwallet::{internal, Error, ErrorKind};
|
||||
use crate::types::{WalletConfig, WalletSeed};
|
||||
use crate::util;
|
||||
use crate::util::secp::constants::SECRET_KEY_SIZE;
|
||||
use crate::util::ZeroingString;
|
||||
|
||||
pub const DB_DIR: &'static str = "db";
|
||||
pub const TX_SAVE_DIR: &'static str = "saved_txs";
|
||||
|
||||
const OUTPUT_PREFIX: u8 = 'o' as u8;
|
||||
const DERIV_PREFIX: u8 = 'd' as u8;
|
||||
const CONFIRMED_HEIGHT_PREFIX: u8 = 'c' as u8;
|
||||
const PRIVATE_TX_CONTEXT_PREFIX: u8 = 'p' as u8;
|
||||
const TX_LOG_ENTRY_PREFIX: u8 = 't' as u8;
|
||||
const TX_LOG_ID_PREFIX: u8 = 'i' as u8;
|
||||
const ACCOUNT_PATH_MAPPING_PREFIX: u8 = 'a' as u8;
|
||||
|
||||
impl From<store::Error> for Error {
|
||||
fn from(error: store::Error) -> Error {
|
||||
Error::from(ErrorKind::Backend(format!("{}", error)))
|
||||
}
|
||||
}
|
||||
|
||||
/// test to see if database files exist in the current directory. If so,
|
||||
/// use a DB backend for all operations
|
||||
pub fn wallet_db_exists(config: WalletConfig) -> bool {
|
||||
let db_path = path::Path::new(&config.data_file_dir).join(DB_DIR);
|
||||
db_path.exists()
|
||||
}
|
||||
|
||||
/// Helper to derive XOR keys for storing private transaction keys in the DB
|
||||
/// (blind_xor_key, nonce_xor_key)
|
||||
fn private_ctx_xor_keys<K>(
|
||||
keychain: &K,
|
||||
slate_id: &[u8],
|
||||
) -> Result<([u8; SECRET_KEY_SIZE], [u8; SECRET_KEY_SIZE]), Error>
|
||||
where
|
||||
K: Keychain,
|
||||
{
|
||||
let root_key = keychain.derive_key(0, &K::root_key_id())?;
|
||||
|
||||
// derive XOR values for storing secret values in DB
|
||||
// h(root_key|slate_id|"blind")
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
hasher.update(&slate_id[..]);
|
||||
hasher.update(&"blind".as_bytes()[..]);
|
||||
let blind_xor_key = hasher.finalize();
|
||||
let mut ret_blind = [0; SECRET_KEY_SIZE];
|
||||
ret_blind.copy_from_slice(&blind_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
|
||||
|
||||
// h(root_key|slate_id|"nonce")
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
hasher.update(&slate_id[..]);
|
||||
hasher.update(&"nonce".as_bytes()[..]);
|
||||
let nonce_xor_key = hasher.finalize();
|
||||
let mut ret_nonce = [0; SECRET_KEY_SIZE];
|
||||
ret_nonce.copy_from_slice(&nonce_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
|
||||
|
||||
Ok((ret_blind, ret_nonce))
|
||||
}
|
||||
|
||||
pub struct LMDBBackend<C, K> {
|
||||
db: store::Store,
|
||||
config: WalletConfig,
|
||||
/// passphrase: TODO better ways of dealing with this other than storing
|
||||
passphrase: ZeroingString,
|
||||
/// Keychain
|
||||
pub keychain: Option<K>,
|
||||
/// Parent path to use by default for output operations
|
||||
parent_key_id: Identifier,
|
||||
/// wallet to node client
|
||||
w2n_client: C,
|
||||
}
|
||||
|
||||
impl<C, K> LMDBBackend<C, K> {
|
||||
pub fn new(config: WalletConfig, passphrase: &str, n_client: C) -> Result<Self, Error> {
|
||||
let db_path = path::Path::new(&config.data_file_dir).join(DB_DIR);
|
||||
fs::create_dir_all(&db_path).expect("Couldn't create wallet backend directory!");
|
||||
|
||||
let stored_tx_path = path::Path::new(&config.data_file_dir).join(TX_SAVE_DIR);
|
||||
fs::create_dir_all(&stored_tx_path)
|
||||
.expect("Couldn't create wallet backend tx storage directory!");
|
||||
|
||||
let lmdb_env = Arc::new(store::new_env(db_path.to_str().unwrap().to_string()));
|
||||
let store = store::Store::open(lmdb_env, DB_DIR);
|
||||
|
||||
// Make sure default wallet derivation path always exists
|
||||
// as well as path (so it can be retrieved by batches to know where to store
|
||||
// completed transactions, for reference
|
||||
let default_account = AcctPathMapping {
|
||||
label: "default".to_owned(),
|
||||
path: LMDBBackend::<C, K>::default_path(),
|
||||
};
|
||||
let acct_key = to_key(
|
||||
ACCOUNT_PATH_MAPPING_PREFIX,
|
||||
&mut default_account.label.as_bytes().to_vec(),
|
||||
);
|
||||
|
||||
{
|
||||
let batch = store.batch()?;
|
||||
batch.put_ser(&acct_key, &default_account)?;
|
||||
batch.commit()?;
|
||||
}
|
||||
|
||||
let res = LMDBBackend {
|
||||
db: store,
|
||||
config: config.clone(),
|
||||
passphrase: ZeroingString::from(passphrase),
|
||||
keychain: None,
|
||||
parent_key_id: LMDBBackend::<C, K>::default_path(),
|
||||
w2n_client: n_client,
|
||||
};
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn default_path() -> Identifier {
|
||||
// return the default parent wallet path, corresponding to the default account
|
||||
// in the BIP32 spec. Parent is account 0 at level 2, child output identifiers
|
||||
// are all at level 3
|
||||
ExtKeychain::derive_key_id(2, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Just test to see if database files exist in the current directory. If
|
||||
/// so, use a DB backend for all operations
|
||||
pub fn exists(config: WalletConfig) -> bool {
|
||||
let db_path = path::Path::new(&config.data_file_dir).join(DB_DIR);
|
||||
db_path.exists()
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, K> WalletBackend<C, K> for LMDBBackend<C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// Initialise with whatever stored credentials we have
|
||||
fn open_with_credentials(&mut self) -> Result<(), Error> {
|
||||
let wallet_seed = WalletSeed::from_file(&self.config, &self.passphrase)
|
||||
.context(ErrorKind::CallbackImpl("Error opening wallet"))?;
|
||||
self.keychain = Some(
|
||||
wallet_seed
|
||||
.derive_keychain(global::is_floonet())
|
||||
.context(ErrorKind::CallbackImpl("Error deriving keychain"))?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close wallet and remove any stored credentials (TBD)
|
||||
fn close(&mut self) -> Result<(), Error> {
|
||||
self.keychain = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the keychain being used
|
||||
fn keychain(&mut self) -> &mut K {
|
||||
self.keychain.as_mut().unwrap()
|
||||
}
|
||||
|
||||
/// Return the node client being used
|
||||
fn w2n_client(&mut self) -> &mut C {
|
||||
&mut self.w2n_client
|
||||
}
|
||||
|
||||
/// return the version of the commit for caching
|
||||
fn calc_commit_for_cache(
|
||||
&mut self,
|
||||
amount: u64,
|
||||
id: &Identifier,
|
||||
) -> Result<Option<String>, Error> {
|
||||
if self.config.no_commit_cache == Some(true) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(util::to_hex(
|
||||
self.keychain().commit(amount, &id)?.0.to_vec(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set parent path by account name
|
||||
fn set_parent_key_id_by_name(&mut self, label: &str) -> Result<(), Error> {
|
||||
let label = label.to_owned();
|
||||
let res = self.acct_path_iter().find(|l| l.label == label);
|
||||
if let Some(a) = res {
|
||||
self.set_parent_key_id(a.path);
|
||||
Ok(())
|
||||
} else {
|
||||
return Err(ErrorKind::UnknownAccountLabel(label.clone()).into());
|
||||
}
|
||||
}
|
||||
|
||||
/// set parent path
|
||||
fn set_parent_key_id(&mut self, id: Identifier) {
|
||||
self.parent_key_id = id;
|
||||
}
|
||||
|
||||
fn parent_key_id(&mut self) -> Identifier {
|
||||
self.parent_key_id.clone()
|
||||
}
|
||||
|
||||
fn get(&self, id: &Identifier, mmr_index: &Option<u64>) -> Result<OutputData, Error> {
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
option_to_not_found(self.db.get_ser(&key), &format!("Key Id: {}", id)).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = OutputData> + 'a> {
|
||||
Box::new(self.db.iter(&[OUTPUT_PREFIX]).unwrap())
|
||||
}
|
||||
|
||||
fn get_tx_log_entry(&self, u: &Uuid) -> Result<Option<TxLogEntry>, Error> {
|
||||
let key = to_key(TX_LOG_ENTRY_PREFIX, &mut u.as_bytes().to_vec());
|
||||
self.db.get_ser(&key).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn tx_log_iter<'a>(&'a self) -> Box<dyn Iterator<Item = TxLogEntry> + 'a> {
|
||||
Box::new(self.db.iter(&[TX_LOG_ENTRY_PREFIX]).unwrap())
|
||||
}
|
||||
|
||||
fn get_private_context(&mut self, slate_id: &[u8]) -> Result<Context, Error> {
|
||||
let ctx_key = to_key(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec());
|
||||
let (blind_xor_key, nonce_xor_key) = private_ctx_xor_keys(self.keychain(), slate_id)?;
|
||||
|
||||
let mut ctx: Context = option_to_not_found(
|
||||
self.db.get_ser(&ctx_key),
|
||||
&format!("Slate id: {:x?}", slate_id.to_vec()),
|
||||
)?;
|
||||
|
||||
for i in 0..SECRET_KEY_SIZE {
|
||||
ctx.sec_key.0[i] = ctx.sec_key.0[i] ^ blind_xor_key[i];
|
||||
ctx.sec_nonce.0[i] = ctx.sec_nonce.0[i] ^ nonce_xor_key[i];
|
||||
}
|
||||
|
||||
Ok(ctx)
|
||||
}
|
||||
|
||||
fn acct_path_iter<'a>(&'a self) -> Box<dyn Iterator<Item = AcctPathMapping> + 'a> {
|
||||
Box::new(self.db.iter(&[ACCOUNT_PATH_MAPPING_PREFIX]).unwrap())
|
||||
}
|
||||
|
||||
fn get_acct_path(&self, label: String) -> Result<Option<AcctPathMapping>, Error> {
|
||||
let acct_key = to_key(ACCOUNT_PATH_MAPPING_PREFIX, &mut label.as_bytes().to_vec());
|
||||
self.db.get_ser(&acct_key).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn store_tx(&self, uuid: &str, tx: &Transaction) -> Result<(), Error> {
|
||||
let filename = format!("{}.grintx", uuid);
|
||||
let path = path::Path::new(&self.config.data_file_dir)
|
||||
.join(TX_SAVE_DIR)
|
||||
.join(filename);
|
||||
let path_buf = Path::new(&path).to_path_buf();
|
||||
let mut stored_tx = File::create(path_buf)?;
|
||||
let tx_hex = util::to_hex(ser::ser_vec(tx).unwrap());;
|
||||
stored_tx.write_all(&tx_hex.as_bytes())?;
|
||||
stored_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_stored_tx(&self, entry: &TxLogEntry) -> Result<Option<Transaction>, Error> {
|
||||
let filename = match entry.stored_tx.clone() {
|
||||
Some(f) => f,
|
||||
None => return Ok(None),
|
||||
};
|
||||
let path = path::Path::new(&self.config.data_file_dir)
|
||||
.join(TX_SAVE_DIR)
|
||||
.join(filename);
|
||||
let tx_file = Path::new(&path).to_path_buf();
|
||||
let mut tx_f = File::open(tx_file)?;
|
||||
let mut content = String::new();
|
||||
tx_f.read_to_string(&mut content)?;
|
||||
let tx_bin = util::from_hex(content).unwrap();
|
||||
Ok(Some(
|
||||
ser::deserialize::<Transaction>(&mut &tx_bin[..]).unwrap(),
|
||||
))
|
||||
}
|
||||
|
||||
fn batch<'a>(&'a mut self) -> Result<Box<dyn WalletOutputBatch<K> + 'a>, Error> {
|
||||
Ok(Box::new(Batch {
|
||||
_store: self,
|
||||
db: RefCell::new(Some(self.db.batch()?)),
|
||||
keychain: self.keychain.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn next_child<'a>(&mut self) -> Result<Identifier, Error> {
|
||||
let parent_key_id = self.parent_key_id.clone();
|
||||
let mut deriv_idx = {
|
||||
let batch = self.db.batch()?;
|
||||
let deriv_key = to_key(DERIV_PREFIX, &mut self.parent_key_id.to_bytes().to_vec());
|
||||
match batch.get_ser(&deriv_key)? {
|
||||
Some(idx) => idx,
|
||||
None => 0,
|
||||
}
|
||||
};
|
||||
let mut return_path = self.parent_key_id.to_path();
|
||||
return_path.depth = return_path.depth + 1;
|
||||
return_path.path[return_path.depth as usize - 1] = ChildNumber::from(deriv_idx);
|
||||
deriv_idx = deriv_idx + 1;
|
||||
let mut batch = self.batch()?;
|
||||
batch.save_child_index(&parent_key_id, deriv_idx)?;
|
||||
batch.commit()?;
|
||||
Ok(Identifier::from_path(&return_path))
|
||||
}
|
||||
|
||||
fn last_confirmed_height<'a>(&mut self) -> Result<u64, Error> {
|
||||
let batch = self.db.batch()?;
|
||||
let height_key = to_key(
|
||||
CONFIRMED_HEIGHT_PREFIX,
|
||||
&mut self.parent_key_id.to_bytes().to_vec(),
|
||||
);
|
||||
let last_confirmed_height = match batch.get_ser(&height_key)? {
|
||||
Some(h) => h,
|
||||
None => 0,
|
||||
};
|
||||
Ok(last_confirmed_height)
|
||||
}
|
||||
|
||||
fn restore(&mut self) -> Result<(), Error> {
|
||||
internal::restore::restore(self).context(ErrorKind::Restore)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_repair(&mut self) -> Result<(), Error> {
|
||||
internal::restore::check_repair(self).context(ErrorKind::Restore)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// An atomic batch in which all changes can be committed all at once or
|
||||
/// discarded on error.
|
||||
pub struct Batch<'a, C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
_store: &'a LMDBBackend<C, K>,
|
||||
db: RefCell<Option<store::Batch<'a>>>,
|
||||
/// Keychain
|
||||
keychain: Option<K>,
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
impl<'a, C, K> WalletOutputBatch<K> for Batch<'a, C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
fn keychain(&mut self) -> &mut K {
|
||||
self.keychain.as_mut().unwrap()
|
||||
}
|
||||
|
||||
fn save(&mut self, out: OutputData) -> Result<(), Error> {
|
||||
// Save the output data to the db.
|
||||
{
|
||||
let key = match out.mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut out.key_id.to_bytes().to_vec(), i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut out.key_id.to_bytes().to_vec()),
|
||||
};
|
||||
self.db.borrow().as_ref().unwrap().put_ser(&key, &out)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get(&self, id: &Identifier, mmr_index: &Option<u64>) -> Result<OutputData, Error> {
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
option_to_not_found(
|
||||
self.db.borrow().as_ref().unwrap().get_ser(&key),
|
||||
&format!("Key ID: {}", id),
|
||||
)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn iter(&self) -> Box<dyn Iterator<Item = OutputData>> {
|
||||
Box::new(
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.iter(&[OUTPUT_PREFIX])
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn delete(&mut self, id: &Identifier, mmr_index: &Option<u64>) -> Result<(), Error> {
|
||||
// Delete the output data.
|
||||
{
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
let _ = self.db.borrow().as_ref().unwrap().delete(&key);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_tx_log_id(&mut self, parent_key_id: &Identifier) -> Result<u32, Error> {
|
||||
let tx_id_key = to_key(TX_LOG_ID_PREFIX, &mut parent_key_id.to_bytes().to_vec());
|
||||
let last_tx_log_id = match self.db.borrow().as_ref().unwrap().get_ser(&tx_id_key)? {
|
||||
Some(t) => t,
|
||||
None => 0,
|
||||
};
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&tx_id_key, &(last_tx_log_id + 1))?;
|
||||
Ok(last_tx_log_id)
|
||||
}
|
||||
|
||||
fn tx_log_iter(&self) -> Box<dyn Iterator<Item = TxLogEntry>> {
|
||||
Box::new(
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.iter(&[TX_LOG_ENTRY_PREFIX])
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn save_last_confirmed_height(
|
||||
&mut self,
|
||||
parent_key_id: &Identifier,
|
||||
height: u64,
|
||||
) -> Result<(), Error> {
|
||||
let height_key = to_key(
|
||||
CONFIRMED_HEIGHT_PREFIX,
|
||||
&mut parent_key_id.to_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&height_key, &height)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_child_index(&mut self, parent_id: &Identifier, child_n: u32) -> Result<(), Error> {
|
||||
let deriv_key = to_key(DERIV_PREFIX, &mut parent_id.to_bytes().to_vec());
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&deriv_key, &child_n)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_tx_log_entry(
|
||||
&mut self,
|
||||
tx_in: TxLogEntry,
|
||||
parent_id: &Identifier,
|
||||
) -> Result<(), Error> {
|
||||
let tx_log_key = to_key_u64(
|
||||
TX_LOG_ENTRY_PREFIX,
|
||||
&mut parent_id.to_bytes().to_vec(),
|
||||
tx_in.id as u64,
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&tx_log_key, &tx_in)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_acct_path(&mut self, mapping: AcctPathMapping) -> Result<(), Error> {
|
||||
let acct_key = to_key(
|
||||
ACCOUNT_PATH_MAPPING_PREFIX,
|
||||
&mut mapping.label.as_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&acct_key, &mapping)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn acct_path_iter(&self) -> Box<dyn Iterator<Item = AcctPathMapping>> {
|
||||
Box::new(
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.iter(&[ACCOUNT_PATH_MAPPING_PREFIX])
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn lock_output(&mut self, out: &mut OutputData) -> Result<(), Error> {
|
||||
out.lock();
|
||||
self.save(out.clone())
|
||||
}
|
||||
|
||||
fn save_private_context(&mut self, slate_id: &[u8], ctx: &Context) -> Result<(), Error> {
|
||||
let ctx_key = to_key(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec());
|
||||
let (blind_xor_key, nonce_xor_key) = private_ctx_xor_keys(self.keychain(), slate_id)?;
|
||||
|
||||
let mut s_ctx = ctx.clone();
|
||||
for i in 0..SECRET_KEY_SIZE {
|
||||
s_ctx.sec_key.0[i] = s_ctx.sec_key.0[i] ^ blind_xor_key[i];
|
||||
s_ctx.sec_nonce.0[i] = s_ctx.sec_nonce.0[i] ^ nonce_xor_key[i];
|
||||
}
|
||||
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&ctx_key, &s_ctx)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_private_context(&mut self, slate_id: &[u8]) -> Result<(), Error> {
|
||||
let ctx_key = to_key(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec());
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.delete(&ctx_key)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn commit(&self) -> Result<(), Error> {
|
||||
let db = self.db.replace(None);
|
||||
db.unwrap().commit()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// 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.
|
||||
|
||||
//! Client functions, implementations of the NodeClient trait
|
||||
//! specific to the FileWallet
|
||||
|
||||
use failure::ResultExt;
|
||||
use futures::{stream, Stream};
|
||||
|
||||
use crate::libwallet::types::*;
|
||||
use std::collections::HashMap;
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
use crate::api;
|
||||
use crate::error::{Error, ErrorKind};
|
||||
use crate::libwallet;
|
||||
use crate::util;
|
||||
use crate::util::secp::pedersen;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HTTPNodeClient {
|
||||
node_url: String,
|
||||
node_api_secret: Option<String>,
|
||||
}
|
||||
|
||||
impl HTTPNodeClient {
|
||||
/// Create a new client that will communicate with the given grin node
|
||||
pub fn new(node_url: &str, node_api_secret: Option<String>) -> HTTPNodeClient {
|
||||
HTTPNodeClient {
|
||||
node_url: node_url.to_owned(),
|
||||
node_api_secret: node_api_secret,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeClient for HTTPNodeClient {
|
||||
fn node_url(&self) -> &str {
|
||||
&self.node_url
|
||||
}
|
||||
fn node_api_secret(&self) -> Option<String> {
|
||||
self.node_api_secret.clone()
|
||||
}
|
||||
|
||||
fn set_node_url(&mut self, node_url: &str) {
|
||||
self.node_url = node_url.to_owned();
|
||||
}
|
||||
|
||||
fn set_node_api_secret(&mut self, node_api_secret: Option<String>) {
|
||||
self.node_api_secret = node_api_secret;
|
||||
}
|
||||
|
||||
/// Posts a transaction to a grin node
|
||||
fn post_tx(&self, tx: &TxWrapper, fluff: bool) -> Result<(), libwallet::Error> {
|
||||
let url;
|
||||
let dest = self.node_url();
|
||||
if fluff {
|
||||
url = format!("{}/v1/pool/push?fluff", dest);
|
||||
} else {
|
||||
url = format!("{}/v1/pool/push", dest);
|
||||
}
|
||||
let res = api::client::post_no_ret(url.as_str(), self.node_api_secret(), tx);
|
||||
if let Err(e) = res {
|
||||
let report = format!("Posting transaction to node: {}", e);
|
||||
error!("Post TX Error: {}", e);
|
||||
return Err(libwallet::ErrorKind::ClientCallback(report).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the chain tip from a given node
|
||||
fn get_chain_height(&self) -> Result<u64, libwallet::Error> {
|
||||
let addr = self.node_url();
|
||||
let url = format!("{}/v1/chain", addr);
|
||||
let res = api::client::get::<api::Tip>(url.as_str(), self.node_api_secret());
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Getting chain height from node: {}", e);
|
||||
error!("Get chain height error: {}", e);
|
||||
Err(libwallet::ErrorKind::ClientCallback(report).into())
|
||||
}
|
||||
Ok(r) => Ok(r.height),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve outputs from node
|
||||
fn get_outputs_from_node(
|
||||
&self,
|
||||
wallet_outputs: Vec<pedersen::Commitment>,
|
||||
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
|
||||
let addr = self.node_url();
|
||||
// build the necessary query params -
|
||||
// ?id=xxx&id=yyy&id=zzz
|
||||
let query_params: Vec<String> = wallet_outputs
|
||||
.iter()
|
||||
.map(|commit| format!("id={}", util::to_hex(commit.as_ref().to_vec())))
|
||||
.collect();
|
||||
|
||||
// build a map of api outputs by commit so we can look them up efficiently
|
||||
let mut api_outputs: HashMap<pedersen::Commitment, (String, u64, u64)> = HashMap::new();
|
||||
let mut tasks = Vec::new();
|
||||
|
||||
for query_chunk in query_params.chunks(500) {
|
||||
let url = format!("{}/v1/chain/outputs/byids?{}", addr, query_chunk.join("&"),);
|
||||
tasks.push(api::client::get_async::<Vec<api::Output>>(
|
||||
url.as_str(),
|
||||
self.node_api_secret(),
|
||||
));
|
||||
}
|
||||
|
||||
let task = stream::futures_unordered(tasks).collect();
|
||||
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
let results = match rt.block_on(task) {
|
||||
Ok(outputs) => outputs,
|
||||
Err(e) => {
|
||||
let report = format!("Getting outputs by id: {}", e);
|
||||
error!("Outputs by id failed: {}", e);
|
||||
return Err(libwallet::ErrorKind::ClientCallback(report).into());
|
||||
}
|
||||
};
|
||||
|
||||
for res in results {
|
||||
for out in res {
|
||||
api_outputs.insert(
|
||||
out.commit.commit(),
|
||||
(util::to_hex(out.commit.to_vec()), out.height, out.mmr_index),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(api_outputs)
|
||||
}
|
||||
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&self,
|
||||
start_height: u64,
|
||||
max_outputs: u64,
|
||||
) -> Result<
|
||||
(
|
||||
u64,
|
||||
u64,
|
||||
Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
|
||||
),
|
||||
libwallet::Error,
|
||||
> {
|
||||
let addr = self.node_url();
|
||||
let query_param = format!("start_index={}&max={}", start_height, max_outputs);
|
||||
|
||||
let url = format!("{}/v1/txhashset/outputs?{}", addr, query_param,);
|
||||
|
||||
let mut api_outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)> =
|
||||
Vec::new();
|
||||
|
||||
match api::client::get::<api::OutputListing>(url.as_str(), self.node_api_secret()) {
|
||||
Ok(o) => {
|
||||
for out in o.outputs {
|
||||
let is_coinbase = match out.output_type {
|
||||
api::OutputType::Coinbase => true,
|
||||
api::OutputType::Transaction => false,
|
||||
};
|
||||
api_outputs.push((
|
||||
out.commit,
|
||||
out.range_proof().unwrap(),
|
||||
is_coinbase,
|
||||
out.block_height.unwrap(),
|
||||
out.mmr_index,
|
||||
));
|
||||
}
|
||||
|
||||
Ok((o.highest_index, o.last_retrieved_index, api_outputs))
|
||||
}
|
||||
Err(e) => {
|
||||
// if we got anything other than 200 back from server, bye
|
||||
error!(
|
||||
"get_outputs_by_pmmr_index: error contacting {}. Error: {}",
|
||||
addr, e
|
||||
);
|
||||
let report = format!("outputs by pmmr index: {}", e);
|
||||
Err(libwallet::ErrorKind::ClientCallback(report))?
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call the wallet API to create a coinbase output for the given block_fees.
|
||||
/// Will retry based on default "retry forever with backoff" behavior.
|
||||
pub fn create_coinbase(dest: &str, block_fees: &BlockFees) -> Result<CbData, Error> {
|
||||
let url = format!("{}/v1/wallet/foreign/build_coinbase", dest);
|
||||
match single_create_coinbase(&url, &block_fees) {
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Failed to get coinbase from {}. Run grin wallet listen?",
|
||||
url
|
||||
);
|
||||
error!("Underlying Error: {}", e.cause().unwrap());
|
||||
error!("Backtrace: {}", e.backtrace().unwrap());
|
||||
Err(e)?
|
||||
}
|
||||
Ok(res) => Ok(res),
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes a single request to the wallet API to create a new coinbase output.
|
||||
fn single_create_coinbase(url: &str, block_fees: &BlockFees) -> Result<CbData, Error> {
|
||||
let res = api::client::post(url, None, block_fees).context(ErrorKind::GenericError(
|
||||
"Posting create coinbase".to_string(),
|
||||
))?;
|
||||
Ok(res)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// 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.
|
||||
|
||||
mod http;
|
||||
|
||||
pub use self::http::{create_coinbase, HTTPNodeClient};
|
||||
@@ -0,0 +1,225 @@
|
||||
// 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 self::chain::Chain;
|
||||
use self::core::core::{OutputFeatures, OutputIdentifier, Transaction};
|
||||
use self::core::{consensus, global, pow, ser};
|
||||
use self::util::secp::pedersen;
|
||||
use self::util::Mutex;
|
||||
use crate::libwallet::api::APIOwner;
|
||||
use crate::libwallet::types::{BlockFees, CbData, NodeClient, WalletInfo, WalletInst};
|
||||
use crate::lmdb_wallet::LMDBBackend;
|
||||
use crate::{controller, libwallet, WalletSeed};
|
||||
use crate::{WalletBackend, WalletConfig};
|
||||
use chrono::Duration;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_util as util;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod testclient;
|
||||
|
||||
pub use self::{testclient::LocalWalletClient, testclient::WalletProxy};
|
||||
|
||||
/// types of backends tests should iterate through
|
||||
//#[derive(Clone)]
|
||||
//pub enum BackendType {
|
||||
// /// File
|
||||
// FileBackend,
|
||||
// /// LMDB
|
||||
// LMDBBackend,
|
||||
//}
|
||||
|
||||
/// Get an output from the chain locally and present it back as an API output
|
||||
fn get_output_local(chain: &chain::Chain, commit: &pedersen::Commitment) -> Option<api::Output> {
|
||||
let outputs = [
|
||||
OutputIdentifier::new(OutputFeatures::Plain, commit),
|
||||
OutputIdentifier::new(OutputFeatures::Coinbase, commit),
|
||||
];
|
||||
|
||||
for x in outputs.iter() {
|
||||
if let Ok(_) = chain.is_unspent(&x) {
|
||||
let block_height = chain.get_header_for_output(&x).unwrap().height;
|
||||
let output_pos = chain.get_output_pos(&x.commit).unwrap_or(0);
|
||||
return Some(api::Output::new(&commit, block_height, output_pos));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// get output listing traversing pmmr from local
|
||||
fn get_outputs_by_pmmr_index_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
max: u64,
|
||||
) -> api::OutputListing {
|
||||
let outputs = chain
|
||||
.unspent_outputs_by_insertion_index(start_index, max)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: outputs.0,
|
||||
highest_index: outputs.1,
|
||||
outputs: outputs
|
||||
.2
|
||||
.iter()
|
||||
.map(|x| api::OutputPrintable::from_output(x, chain.clone(), None, true))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a block with a given reward to the chain and mines it
|
||||
pub fn add_block_with_reward(chain: &Chain, txs: Vec<&Transaction>, reward: CbData) {
|
||||
let prev = chain.head_header().unwrap();
|
||||
let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter());
|
||||
let out_bin = util::from_hex(reward.output).unwrap();
|
||||
let kern_bin = util::from_hex(reward.kernel).unwrap();
|
||||
let output = ser::deserialize(&mut &out_bin[..]).unwrap();
|
||||
let kernel = ser::deserialize(&mut &kern_bin[..]).unwrap();
|
||||
let mut b = core::core::Block::new(
|
||||
&prev,
|
||||
txs.into_iter().cloned().collect(),
|
||||
next_header_info.clone().difficulty,
|
||||
(output, kernel),
|
||||
)
|
||||
.unwrap();
|
||||
b.header.timestamp = prev.timestamp + Duration::seconds(60);
|
||||
b.header.pow.secondary_scaling = next_header_info.secondary_scaling;
|
||||
chain.set_txhashset_roots(&mut b).unwrap();
|
||||
pow::pow_size(
|
||||
&mut b.header,
|
||||
next_header_info.difficulty,
|
||||
global::proofsize(),
|
||||
global::min_edge_bits(),
|
||||
)
|
||||
.unwrap();
|
||||
chain.process_block(b, chain::Options::MINE).unwrap();
|
||||
chain.validate(false).unwrap();
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block, mines
|
||||
/// the block and adds it to the chain, with option transactions included.
|
||||
/// Helpful for building up precise wallet balances for testing.
|
||||
pub fn award_block_to_wallet<C, K>(
|
||||
chain: &Chain,
|
||||
txs: Vec<&Transaction>,
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
// build block fees
|
||||
let prev = chain.head_header().unwrap();
|
||||
let fee_amt = txs.iter().map(|tx| tx.fee()).sum();
|
||||
let block_fees = BlockFees {
|
||||
fees: fee_amt,
|
||||
key_id: None,
|
||||
height: prev.height + 1,
|
||||
};
|
||||
// build coinbase (via api) and add block
|
||||
controller::foreign_single_use(wallet.clone(), |api| {
|
||||
let coinbase_tx = api.build_coinbase(&block_fees)?;
|
||||
add_block_with_reward(chain, txs, coinbase_tx.clone());
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Award a blocks to a wallet directly
|
||||
pub fn award_blocks_to_wallet<C, K>(
|
||||
chain: &Chain,
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
number: usize,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
for _ in 0..number {
|
||||
award_block_to_wallet(chain, vec![], wallet.clone())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// dispatch a db wallet
|
||||
pub fn create_wallet<C, K>(
|
||||
dir: &str,
|
||||
n_client: C,
|
||||
rec_phrase: Option<&str>,
|
||||
) -> Arc<Mutex<dyn WalletInst<C, K>>>
|
||||
where
|
||||
C: NodeClient + 'static,
|
||||
K: keychain::Keychain + 'static,
|
||||
{
|
||||
let z_string = match rec_phrase {
|
||||
Some(s) => Some(util::ZeroingString::from(s)),
|
||||
None => None,
|
||||
};
|
||||
let mut wallet_config = WalletConfig::default();
|
||||
wallet_config.data_file_dir = String::from(dir);
|
||||
let _ = WalletSeed::init_file(&wallet_config, 32, z_string, "");
|
||||
let mut wallet = LMDBBackend::new(wallet_config.clone(), "", n_client)
|
||||
.unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, wallet_config));
|
||||
wallet.open_with_credentials().unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Error initializing wallet: {:?} Config: {:?}",
|
||||
e, wallet_config
|
||||
)
|
||||
});
|
||||
Arc::new(Mutex::new(wallet))
|
||||
}
|
||||
|
||||
/// send an amount to a destination
|
||||
pub fn send_to_dest<T: ?Sized, C, K>(
|
||||
client: LocalWalletClient,
|
||||
api: &mut APIOwner<T, C, K>,
|
||||
dest: &str,
|
||||
amount: u64,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
let (slate_i, lock_fn) = api.initiate_tx(
|
||||
None, // account
|
||||
amount, // amount
|
||||
2, // minimum confirmations
|
||||
500, // max outputs
|
||||
1, // num change outputs
|
||||
true, // select all outputs
|
||||
None,
|
||||
)?;
|
||||
let mut slate = client.send_tx_slate_direct(dest, &slate_i)?;
|
||||
api.tx_lock_outputs(&slate, lock_fn)?;
|
||||
api.finalize_tx(&mut slate)?;
|
||||
api.post_tx(&slate.tx, false)?; // mines a block
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get wallet info totals
|
||||
pub fn wallet_info<T: ?Sized, C, K>(
|
||||
api: &mut APIOwner<T, C, K>,
|
||||
) -> Result<WalletInfo, libwallet::Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
let (wallet_refreshed, wallet_info) = api.retrieve_summary_info(true, 1)?;
|
||||
assert!(wallet_refreshed);
|
||||
Ok(wallet_info)
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
// 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.
|
||||
|
||||
//! Test client that acts against a local instance of a node
|
||||
//! so that wallet API can be fully exercised
|
||||
//! Operates directly on a chain instance
|
||||
|
||||
use self::chain::types::NoopAdapter;
|
||||
use self::chain::Chain;
|
||||
use self::core::core::verifier_cache::LruVerifierCache;
|
||||
use self::core::core::Transaction;
|
||||
use self::core::global::{set_mining_mode, ChainTypes};
|
||||
use self::core::{pow, ser};
|
||||
use self::keychain::Keychain;
|
||||
use self::util::secp::pedersen;
|
||||
use self::util::secp::pedersen::Commitment;
|
||||
use self::util::{Mutex, RwLock, StopState};
|
||||
use crate::libwallet::slate::Slate;
|
||||
use crate::libwallet::types::*;
|
||||
use crate::{controller, libwallet, WalletCommAdapter, WalletConfig};
|
||||
use failure::ResultExt;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_store as store;
|
||||
use grin_util as util;
|
||||
use serde_json;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Messages to simulate wallet requests/responses
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WalletProxyMessage {
|
||||
/// sender ID
|
||||
pub sender_id: String,
|
||||
/// destination wallet (or server)
|
||||
pub dest: String,
|
||||
/// method (like a GET url)
|
||||
pub method: String,
|
||||
/// payload (json body)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// communicates with a chain instance or other wallet
|
||||
/// listener APIs via message queues
|
||||
pub struct WalletProxy<C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// directory to create the chain in
|
||||
pub chain_dir: String,
|
||||
/// handle to chain itself
|
||||
pub chain: Arc<Chain>,
|
||||
/// list of interested wallets
|
||||
pub wallets: HashMap<
|
||||
String,
|
||||
(
|
||||
Sender<WalletProxyMessage>,
|
||||
Arc<Mutex<dyn WalletInst<LocalWalletClient, K>>>,
|
||||
),
|
||||
>,
|
||||
/// simulate json send to another client
|
||||
/// address, method, payload (simulate HTTP request)
|
||||
pub tx: Sender<WalletProxyMessage>,
|
||||
/// simulate json receiving
|
||||
pub rx: Receiver<WalletProxyMessage>,
|
||||
/// queue control
|
||||
pub running: Arc<AtomicBool>,
|
||||
/// Phantom
|
||||
phantom_c: PhantomData<C>,
|
||||
/// Phantom
|
||||
phantom_k: PhantomData<K>,
|
||||
}
|
||||
|
||||
impl<C, K> WalletProxy<C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// Create a new client that will communicate with the given grin node
|
||||
pub fn new(chain_dir: &str) -> Self {
|
||||
set_mining_mode(ChainTypes::AutomatedTesting);
|
||||
let genesis_block = pow::mine_genesis_block().unwrap();
|
||||
let verifier_cache = Arc::new(RwLock::new(LruVerifierCache::new()));
|
||||
let dir_name = format!("{}/.grin", chain_dir);
|
||||
let db_env = Arc::new(store::new_env(dir_name.to_string()));
|
||||
let c = Chain::init(
|
||||
dir_name.to_string(),
|
||||
db_env,
|
||||
Arc::new(NoopAdapter {}),
|
||||
genesis_block,
|
||||
pow::verify_size,
|
||||
verifier_cache,
|
||||
false,
|
||||
Arc::new(Mutex::new(StopState::new())),
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, rx) = channel();
|
||||
let retval = WalletProxy {
|
||||
chain_dir: chain_dir.to_owned(),
|
||||
chain: Arc::new(c),
|
||||
tx: tx,
|
||||
rx: rx,
|
||||
wallets: HashMap::new(),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
phantom_c: PhantomData,
|
||||
phantom_k: PhantomData,
|
||||
};
|
||||
retval
|
||||
}
|
||||
|
||||
/// Add wallet with a given "address"
|
||||
pub fn add_wallet(
|
||||
&mut self,
|
||||
addr: &str,
|
||||
tx: Sender<WalletProxyMessage>,
|
||||
wallet: Arc<Mutex<dyn WalletInst<LocalWalletClient, K>>>,
|
||||
) {
|
||||
self.wallets.insert(addr.to_owned(), (tx, wallet));
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
self.running.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Run the incoming message queue and respond more or less
|
||||
/// synchronously
|
||||
pub fn run(&mut self) -> Result<(), libwallet::Error> {
|
||||
self.running.store(true, Ordering::Relaxed);
|
||||
loop {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
// read queue
|
||||
let m = self.rx.recv().unwrap();
|
||||
trace!("Wallet Client Proxy Received: {:?}", m);
|
||||
let resp = match m.method.as_ref() {
|
||||
"get_chain_height" => self.get_chain_height(m)?,
|
||||
"get_outputs_from_node" => self.get_outputs_from_node(m)?,
|
||||
"get_outputs_by_pmmr_index" => self.get_outputs_by_pmmr_index(m)?,
|
||||
"send_tx_slate" => self.send_tx_slate(m)?,
|
||||
"post_tx" => self.post_tx(m)?,
|
||||
_ => panic!("Unknown Wallet Proxy Message"),
|
||||
};
|
||||
|
||||
self.respond(resp);
|
||||
if !self.running.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a message to a given wallet client
|
||||
fn respond(&mut self, m: WalletProxyMessage) {
|
||||
if let Some(s) = self.wallets.get_mut(&m.dest) {
|
||||
if let Err(e) = s.0.send(m.clone()) {
|
||||
panic!("Error sending response from proxy: {:?}, {}", m, e);
|
||||
}
|
||||
} else {
|
||||
panic!("Unknown wallet recipient for response message: {:?}", m);
|
||||
}
|
||||
}
|
||||
|
||||
/// post transaction to the chain (and mine it, taking the reward)
|
||||
fn post_tx(&mut self, m: WalletProxyMessage) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let dest_wallet = self.wallets.get_mut(&m.sender_id).unwrap().1.clone();
|
||||
let wrapper: TxWrapper = serde_json::from_str(&m.body).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper".to_owned()),
|
||||
)?;
|
||||
|
||||
let tx_bin = util::from_hex(wrapper.tx_hex).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper: tx_bin".to_owned()),
|
||||
)?;
|
||||
|
||||
let tx: Transaction = ser::deserialize(&mut &tx_bin[..]).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper: tx".to_owned()),
|
||||
)?;
|
||||
|
||||
super::award_block_to_wallet(&self.chain, vec![&tx], dest_wallet)?;
|
||||
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: "".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// send tx slate
|
||||
fn send_tx_slate(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let dest_wallet = self.wallets.get_mut(&m.dest);
|
||||
if let None = dest_wallet {
|
||||
panic!("Unknown wallet destination for send_tx_slate: {:?}", m);
|
||||
}
|
||||
let w = dest_wallet.unwrap().1.clone();
|
||||
let mut slate = serde_json::from_str(&m.body).unwrap();
|
||||
controller::foreign_single_use(w.clone(), |listener_api| {
|
||||
listener_api.receive_tx(&mut slate, None, None)?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: m.dest,
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&slate).unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get chain height
|
||||
fn get_chain_height(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: format!("{}", self.chain.head().unwrap().height).to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get api outputs
|
||||
fn get_outputs_from_node(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let split = m.body.split(",");
|
||||
//let mut api_outputs: HashMap<pedersen::Commitment, String> = HashMap::new();
|
||||
let mut outputs: Vec<api::Output> = vec![];
|
||||
for o in split {
|
||||
let o_str = String::from(o);
|
||||
if o_str.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
let c = util::from_hex(o_str).unwrap();
|
||||
let commit = Commitment::from_vec(c);
|
||||
let out = super::get_output_local(&self.chain.clone(), &commit);
|
||||
if let Some(o) = out {
|
||||
outputs.push(o);
|
||||
}
|
||||
}
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&outputs).unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get api outputs
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let split = m.body.split(",").collect::<Vec<&str>>();
|
||||
let start_index = split[0].parse::<u64>().unwrap();
|
||||
let max = split[1].parse::<u64>().unwrap();
|
||||
let ol = super::get_outputs_by_pmmr_index_local(self.chain.clone(), start_index, max);
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&ol).unwrap(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct LocalWalletClient {
|
||||
/// wallet identifier for the proxy queue
|
||||
pub id: String,
|
||||
/// proxy's tx queue (receive messages from other wallets or node
|
||||
pub proxy_tx: Arc<Mutex<Sender<WalletProxyMessage>>>,
|
||||
/// my rx queue
|
||||
pub rx: Arc<Mutex<Receiver<WalletProxyMessage>>>,
|
||||
/// my tx queue
|
||||
pub tx: Arc<Mutex<Sender<WalletProxyMessage>>>,
|
||||
}
|
||||
|
||||
impl LocalWalletClient {
|
||||
/// new
|
||||
pub fn new(id: &str, proxy_rx: Sender<WalletProxyMessage>) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
LocalWalletClient {
|
||||
id: id.to_owned(),
|
||||
proxy_tx: Arc::new(Mutex::new(proxy_rx)),
|
||||
rx: Arc::new(Mutex::new(rx)),
|
||||
tx: Arc::new(Mutex::new(tx)),
|
||||
}
|
||||
}
|
||||
|
||||
/// get an instance of the send queue for other senders
|
||||
pub fn get_send_instance(&self) -> Sender<WalletProxyMessage> {
|
||||
self.tx.lock().clone()
|
||||
}
|
||||
|
||||
/// Send the slate to a listening wallet instance
|
||||
pub fn send_tx_slate_direct(
|
||||
&self,
|
||||
dest: &str,
|
||||
slate: &Slate,
|
||||
) -> Result<Slate, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: dest.to_owned(),
|
||||
method: "send_tx_slate".to_owned(),
|
||||
body: serde_json::to_string(slate).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Send TX Slate".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received send_tx_slate response: {:?}", m.clone());
|
||||
Ok(
|
||||
serde_json::from_str(&m.body).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing send_tx_slate response".to_owned(),
|
||||
))?,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for LocalWalletClient {
|
||||
fn supports_sync(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Send the slate to a listening wallet instance
|
||||
fn send_tx_sync(&self, dest: &str, slate: &Slate) -> Result<Slate, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: dest.to_owned(),
|
||||
method: "send_tx_slate".to_owned(),
|
||||
body: serde_json::to_string(slate).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Send TX Slate".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received send_tx_slate response: {:?}", m.clone());
|
||||
Ok(
|
||||
serde_json::from_str(&m.body).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing send_tx_slate response".to_owned(),
|
||||
))?,
|
||||
)
|
||||
}
|
||||
|
||||
fn send_tx_async(&self, _dest: &str, _slate: &Slate) -> Result<(), libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn receive_tx_async(&self, _params: &str) -> Result<Slate, libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn listen(
|
||||
&self,
|
||||
_params: HashMap<String, String>,
|
||||
_config: WalletConfig,
|
||||
_passphrase: &str,
|
||||
_account: &str,
|
||||
_node_api_secret: Option<String>,
|
||||
) -> Result<(), libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeClient for LocalWalletClient {
|
||||
fn node_url(&self) -> &str {
|
||||
"node"
|
||||
}
|
||||
fn node_api_secret(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn set_node_url(&mut self, _node_url: &str) {}
|
||||
fn set_node_api_secret(&mut self, _node_api_secret: Option<String>) {}
|
||||
/// Posts a transaction to a grin node
|
||||
/// In this case it will create a new block with award rewarded to
|
||||
fn post_tx(&self, tx: &TxWrapper, _fluff: bool) -> Result<(), libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "post_tx".to_owned(),
|
||||
body: serde_json::to_string(tx).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"post_tx send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received post_tx response: {:?}", m.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the chain tip from a given node
|
||||
fn get_chain_height(&self) -> Result<u64, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_chain_height".to_owned(),
|
||||
body: "".to_owned(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get chain height send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received get_chain_height response: {:?}", m.clone());
|
||||
Ok(m.body
|
||||
.parse::<u64>()
|
||||
.context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing get_height response".to_owned(),
|
||||
))?)
|
||||
}
|
||||
|
||||
/// Retrieve outputs from node
|
||||
fn get_outputs_from_node(
|
||||
&self,
|
||||
wallet_outputs: Vec<pedersen::Commitment>,
|
||||
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
|
||||
let query_params: Vec<String> = wallet_outputs
|
||||
.iter()
|
||||
.map(|commit| format!("{}", util::to_hex(commit.as_ref().to_vec())))
|
||||
.collect();
|
||||
let query_str = query_params.join(",");
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_outputs_from_node".to_owned(),
|
||||
body: query_str,
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get outputs from node send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
let outputs: Vec<api::Output> = serde_json::from_str(&m.body).unwrap();
|
||||
let mut api_outputs: HashMap<pedersen::Commitment, (String, u64, u64)> = HashMap::new();
|
||||
for out in outputs {
|
||||
api_outputs.insert(
|
||||
out.commit.commit(),
|
||||
(util::to_hex(out.commit.to_vec()), out.height, out.mmr_index),
|
||||
);
|
||||
}
|
||||
Ok(api_outputs)
|
||||
}
|
||||
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&self,
|
||||
start_height: u64,
|
||||
max_outputs: u64,
|
||||
) -> Result<
|
||||
(
|
||||
u64,
|
||||
u64,
|
||||
Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
|
||||
),
|
||||
libwallet::Error,
|
||||
> {
|
||||
// start index, max
|
||||
let query_str = format!("{},{}", start_height, max_outputs);
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_outputs_by_pmmr_index".to_owned(),
|
||||
body: query_str,
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get outputs from node by PMMR index send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
let o: api::OutputListing = serde_json::from_str(&m.body).unwrap();
|
||||
|
||||
let mut api_outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)> =
|
||||
Vec::new();
|
||||
|
||||
for out in o.outputs {
|
||||
let is_coinbase = match out.output_type {
|
||||
api::OutputType::Coinbase => true,
|
||||
api::OutputType::Transaction => false,
|
||||
};
|
||||
api_outputs.push((
|
||||
out.commit,
|
||||
out.range_proof().unwrap(),
|
||||
is_coinbase,
|
||||
out.block_height.unwrap(),
|
||||
out.mmr_index,
|
||||
));
|
||||
}
|
||||
Ok((o.highest_index, o.last_retrieved_index, api_outputs))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
// 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::core::global::ChainTypes;
|
||||
use crate::error::{Error, ErrorKind};
|
||||
use crate::keychain::{mnemonic, Keychain};
|
||||
use crate::util;
|
||||
use failure::ResultExt;
|
||||
|
||||
pub const SEED_FILE: &'static str = "wallet.seed";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct WalletConfig {
|
||||
// Chain parameters (default to Testnet3 if none at the moment)
|
||||
pub chain_type: Option<ChainTypes>,
|
||||
// The api interface/ip_address that this api server (i.e. this wallet) will run
|
||||
// by default this is 127.0.0.1 (and will not accept connections from external clients)
|
||||
pub api_listen_interface: String,
|
||||
// The port this wallet will run on
|
||||
pub api_listen_port: u16,
|
||||
// The port this wallet's owner API will run on
|
||||
pub owner_api_listen_port: Option<u16>,
|
||||
/// Location of the secret for basic auth on the Owner API
|
||||
pub api_secret_path: Option<String>,
|
||||
/// Location of the node api secret for basic auth on the Grin API
|
||||
pub node_api_secret_path: Option<String>,
|
||||
// The api address of a running server node against which transaction inputs
|
||||
// will be checked during send
|
||||
pub check_node_api_http_addr: String,
|
||||
// Whether to include foreign API endpoints on the Owner API
|
||||
pub owner_api_include_foreign: Option<bool>,
|
||||
// The directory in which wallet files are stored
|
||||
pub data_file_dir: String,
|
||||
/// If Some(true), don't cache commits alongside output data
|
||||
/// speed improvement, but your commits are in the database
|
||||
pub no_commit_cache: Option<bool>,
|
||||
/// TLS certificate file
|
||||
pub tls_certificate_file: Option<String>,
|
||||
/// TLS certificate private key file
|
||||
pub tls_certificate_key: Option<String>,
|
||||
/// Whether to use the black background color scheme for command line
|
||||
/// if enabled, wallet command output color will be suitable for black background terminal
|
||||
pub dark_background_color_scheme: Option<bool>,
|
||||
// The exploding lifetime (minutes) for keybase notification on coins received
|
||||
pub keybase_notify_ttl: Option<u16>,
|
||||
}
|
||||
|
||||
impl Default for WalletConfig {
|
||||
fn default() -> WalletConfig {
|
||||
WalletConfig {
|
||||
chain_type: Some(ChainTypes::Mainnet),
|
||||
api_listen_interface: "127.0.0.1".to_string(),
|
||||
api_listen_port: 3415,
|
||||
owner_api_listen_port: Some(WalletConfig::default_owner_api_listen_port()),
|
||||
api_secret_path: Some(".api_secret".to_string()),
|
||||
node_api_secret_path: Some(".api_secret".to_string()),
|
||||
check_node_api_http_addr: "http://127.0.0.1:3413".to_string(),
|
||||
owner_api_include_foreign: Some(false),
|
||||
data_file_dir: ".".to_string(),
|
||||
no_commit_cache: Some(false),
|
||||
tls_certificate_file: None,
|
||||
tls_certificate_key: None,
|
||||
dark_background_color_scheme: Some(true),
|
||||
keybase_notify_ttl: Some(1440),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletConfig {
|
||||
pub fn api_listen_addr(&self) -> String {
|
||||
format!("{}:{}", self.api_listen_interface, self.api_listen_port)
|
||||
}
|
||||
|
||||
pub fn default_owner_api_listen_port() -> u16 {
|
||||
3420
|
||||
}
|
||||
|
||||
/// Use value from config file, defaulting to sensible value if missing.
|
||||
pub fn owner_api_listen_port(&self) -> u16 {
|
||||
self.owner_api_listen_port
|
||||
.unwrap_or(WalletConfig::default_owner_api_listen_port())
|
||||
}
|
||||
|
||||
pub fn owner_api_listen_addr(&self) -> String {
|
||||
format!("127.0.0.1:{}", self.owner_api_listen_port())
|
||||
}
|
||||
}
|
||||
|
||||
#[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: &str) -> 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(wallet_config: &WalletConfig) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
wallet_config.data_file_dir, MAIN_SEPARATOR, SEED_FILE,
|
||||
);
|
||||
if Path::new(seed_file_path).exists() {
|
||||
return Err(ErrorKind::WalletSeedExists(seed_file_path.to_owned()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn backup_seed(wallet_config: &WalletConfig) -> Result<(), Error> {
|
||||
let seed_file_name = &format!(
|
||||
"{}{}{}",
|
||||
wallet_config.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",
|
||||
wallet_config.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.{}",
|
||||
wallet_config.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(
|
||||
wallet_config: &WalletConfig,
|
||||
word_list: &str,
|
||||
password: &str,
|
||||
) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
wallet_config.data_file_dir, MAIN_SEPARATOR, SEED_FILE,
|
||||
);
|
||||
if WalletSeed::seed_file_exists(wallet_config).is_err() {
|
||||
WalletSeed::backup_seed(wallet_config)?;
|
||||
}
|
||||
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 show_recovery_phrase(&self) -> Result<(), Error> {
|
||||
println!("Your recovery phrase is:");
|
||||
println!();
|
||||
println!("{}", self.to_mnemonic()?);
|
||||
println!();
|
||||
println!("Please back-up these words in a non-digital format.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn init_file(
|
||||
wallet_config: &WalletConfig,
|
||||
seed_length: usize,
|
||||
recovery_phrase: Option<util::ZeroingString>,
|
||||
password: &str,
|
||||
) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(&wallet_config.data_file_dir).context(ErrorKind::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
wallet_config.data_file_dir, MAIN_SEPARATOR, SEED_FILE,
|
||||
);
|
||||
|
||||
warn!("Generating wallet seed file at: {}", seed_file_path);
|
||||
let _ = WalletSeed::seed_file_exists(wallet_config)?;
|
||||
|
||||
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)?;
|
||||
seed.show_recovery_phrase()?;
|
||||
Ok(seed)
|
||||
}
|
||||
|
||||
pub fn from_file(wallet_config: &WalletConfig, password: &str) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(&wallet_config.data_file_dir).context(ErrorKind::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
wallet_config.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: &str) -> 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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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.
|
||||
|
||||
//! Build hooks to spit out version+build time info
|
||||
|
||||
use built;
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
// Setting up git hooks in the project: rustfmt and so on.
|
||||
let git_hooks = format!(
|
||||
"git config core.hooksPath {}",
|
||||
PathBuf::from("./.hooks").to_str().unwrap()
|
||||
);
|
||||
|
||||
if cfg!(target_os = "windows") {
|
||||
Command::new("cmd")
|
||||
.args(&["/C", &git_hooks])
|
||||
.output()
|
||||
.expect("failed to execute git config for hooks");
|
||||
} else {
|
||||
Command::new("sh")
|
||||
.args(&["-c", &git_hooks])
|
||||
.output()
|
||||
.expect("failed to execute git config for hooks");
|
||||
}
|
||||
|
||||
// build and versioning information
|
||||
let mut opts = built::Options::default();
|
||||
opts.set_dependencies(true);
|
||||
// don't fail the build if something's missing, may just be cargo release
|
||||
let _ = built::write_built_file_with_opts(
|
||||
&opts,
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
format!("{}{}", env::var("OUT_DIR").unwrap(), "/built.rs"),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user