mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-12-03 04:13:57 +01:00
APIV2 refactoring (#23)
* continue refactor * rustfmt * further refactoring * impl crate compiling * main crate compilation * rustfmt * test fix * rustfmt * test compilation * rustfmt * refwallet tests passing * rustfmt * all tests passing * move http listener startup out of adapter * rustfmt * rename refwallet->controller * rustfmt * travis tests and api doctests * rustfmt
This commit is contained in:
@@ -0,0 +1,589 @@
|
||||
// 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::config::WalletConfig;
|
||||
use crate::error::{Error, ErrorKind};
|
||||
use crate::impls::{
|
||||
instantiate_wallet, FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter,
|
||||
LMDBBackend, NullWalletCommAdapter,
|
||||
};
|
||||
use crate::impls::{HTTPNodeClient, WalletSeed};
|
||||
use crate::libwallet::types::{NodeClient, WalletInst};
|
||||
use crate::{controller, display};
|
||||
|
||||
/// 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.into());
|
||||
}
|
||||
let _ = res.unwrap().show_recovery_phrase();
|
||||
} else {
|
||||
let res = WalletSeed::recover_from_phrase(
|
||||
&config,
|
||||
&args.recovery_phrase.as_ref().unwrap(),
|
||||
&args.passphrase,
|
||||
);
|
||||
if let Err(e) = res {
|
||||
error!("Error recovering seed - {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
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 res = match args.method.as_str() {
|
||||
"http" => {
|
||||
// HTTP adapter can't use the listen trait method because of the
|
||||
// crate structure. May be able to fix when V1 API is deprecated
|
||||
let node_client = HTTPNodeClient::new(
|
||||
&config.check_node_api_http_addr,
|
||||
g_args.node_api_secret.clone(),
|
||||
);
|
||||
let wallet = instantiate_wallet(
|
||||
config.clone(),
|
||||
node_client,
|
||||
&g_args.password.clone().unwrap(),
|
||||
&g_args.account,
|
||||
)?;
|
||||
let listen_addr = params.get("api_listen_addr").unwrap();
|
||||
let tls_conf = match params.get("certificate") {
|
||||
Some(s) => Some(grin_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(())
|
||||
}
|
||||
"keybase" => {
|
||||
let adapter = KeybaseWalletCommAdapter::new();
|
||||
adapter.listen(
|
||||
params,
|
||||
config.clone(),
|
||||
&g_args.password.clone().unwrap(),
|
||||
&g_args.account,
|
||||
g_args.node_api_secret.clone(),
|
||||
)
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
|
||||
if let Err(e) = res {
|
||||
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 target_slate_version: Option<u16>,
|
||||
}
|
||||
|
||||
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(),
|
||||
args.target_slate_version,
|
||||
);
|
||||
let mut slate = 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)?;
|
||||
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)?;
|
||||
}
|
||||
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(())
|
||||
}
|
||||
|
||||
/// wallet check
|
||||
pub struct CheckArgs {
|
||||
pub delete_unconfirmed: bool,
|
||||
}
|
||||
|
||||
pub fn check_repair(
|
||||
wallet: Arc<Mutex<WalletInst<impl NodeClient + 'static, keychain::ExtKeychain>>>,
|
||||
args: CheckArgs,
|
||||
) -> 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(args.delete_unconfirmed);
|
||||
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,824 @@
|
||||
// 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::api::{ApiServer, BasicAuthMiddleware, Handler, ResponseFuture, Router, TLSConfig};
|
||||
use crate::apiwallet::{Foreign, Owner};
|
||||
use crate::core::core;
|
||||
use crate::core::core::Transaction;
|
||||
use crate::impls::{FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter};
|
||||
use crate::keychain::Keychain;
|
||||
use crate::libwallet::slate::Slate;
|
||||
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 Owner<T, C, K>) -> Result<(), Error>,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
f(&mut Owner::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 Foreign<T, C, K>) -> Result<(), Error>,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
f(&mut Foreign::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: Owner<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: Owner<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: Owner<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>,
|
||||
api: Owner<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>,
|
||||
api: Owner<T, C, K>,
|
||||
) -> Result<(u64, bool), Error> {
|
||||
api.node_height()
|
||||
}
|
||||
|
||||
fn handle_get_request(&self, req: &Request<Body>) -> Result<Response<Body>, Error> {
|
||||
let api = Owner::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>,
|
||||
api: Owner<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,
|
||||
args.target_slate_version,
|
||||
);
|
||||
let mut slate = 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)?;
|
||||
if args.method != "file" {
|
||||
api.finalize_tx(&mut slate)?;
|
||||
}
|
||||
Ok(slate)
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn finalize_tx(
|
||||
&self,
|
||||
req: Request<Body>,
|
||||
api: Owner<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>,
|
||||
api: Owner<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: Owner<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: Owner<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 = Owner::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>,
|
||||
api: Foreign<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>,
|
||||
api: Foreign<T, C, K>,
|
||||
) -> Box<dyn Future<Item = String, Error = Error> + Send> {
|
||||
Box::new(parse_body(req).and_then(
|
||||
//TODO: No way to insert a message from the params
|
||||
move |slate_str: String| {
|
||||
let mut slate: Slate = Slate::deserialize_upgrade(&slate_str).unwrap();
|
||||
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(slate
|
||||
.serialize_to_version(Some(slate.version_info.orig_version))
|
||||
.unwrap()),
|
||||
Err(e) => {
|
||||
error!("receive_tx: failed with error: {}", e);
|
||||
err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn handle_request(&self, req: Request<Body>) -> WalletResponseFuture {
|
||||
let api = *Foreign::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,480 @@
|
||||
// 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->"Confirmed 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![
|
||||
bFB->format!("Awaiting Finalization"),
|
||||
FB->amount_to_hr_string(wallet_info.amount_awaiting_finalization, 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,223 @@
|
||||
// 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::impls;
|
||||
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),
|
||||
|
||||
/// Impls error
|
||||
#[fail(display = "Impls Error")]
|
||||
Impls(impls::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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<impls::Error> for Error {
|
||||
fn from(error: impls::Error) -> Error {
|
||||
Error {
|
||||
inner: Context::new(ErrorKind::Impls(error.kind())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// 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.
|
||||
|
||||
#[macro_use]
|
||||
extern crate prettytable;
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
use failure;
|
||||
use grin_api as api;
|
||||
extern crate grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_util as util;
|
||||
use grin_wallet_api as apiwallet;
|
||||
use grin_wallet_impls as impls;
|
||||
use grin_wallet_libwallet as libwallet;
|
||||
extern crate grin_wallet_config as config;
|
||||
|
||||
pub mod command;
|
||||
pub mod controller;
|
||||
pub mod display;
|
||||
mod error;
|
||||
|
||||
pub use crate::error::{Error, ErrorKind};
|
||||
Reference in New Issue
Block a user