Files
grin-wallet/src/cmd/wallet_args.rs
T
wiescheGitHubJoergardocratdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
90846a4212 Mwixnet wallet support (#783)
* Update rust edition to 2021 (#749)

* build: update rust edition 2021

* cargo: format all

* build: fix tests and warnings

* Save last scanned block info for wallet scanning (#748)

* scan: save last scanned block info for initial wallet scanning

* scan: save start height at scanned block info on outputs collecting

* scan: 10k blocks batches

* fix: include last height into batch on scan

* scan: save hash of last block

* scan: add larger window (2880 blocks) to scan outputs when updating wallet state

* add test batched scan and resume, add scan doc

* rename corrupted restore test

---------

Co-authored-by: Joerg <wiesche89@googlemail.com>

* Bump openssl from 0.10.68 to 0.10.80 (#752)

* Update lmdb (#755)

* wallet: update lmdb from store crate, migrate single backend from trait to struct, update tests cargo deps and design doc

* backend: do not panic on iter and directory creation

* return  iterator errors

* build: update to last node revision

* fix: height selection for scan, remove unused mutability for wallet

* wallet: remove unused mutability conversion

* tx: store slate state at database

* build: cargo fmt

* fix: do not return error when slate not found on tx slate state update

* lmdb: do not collect all tx log records at iterator, show read errors at log

* fix: save slate state, return error if slate not found

* tx: specify amount of bad txs on slate state update error

---------

Co-authored-by: Joerg <wiesche89@googlemail.com>

* Node submodules (#758)

* build: use node submodule as dependency

* ci: checkout submodules

* docs: add contributing and build instruction

* ci: update release build

* git: remove old submodule

* git: grin staging submodule

* git: add submodule dir

* Integrated Tor arti Client (#750)

* tor: integrated client for listener, update tokio to last version

* tor: send transaction with integrated client

* build: code format

* tor: optimize bootstrap percent check

* tor: handle config build error

* tor: do not show slatepack address if tor not launched

* tor: handle keystore errors

* tor: keep service launched

* tor: bootstrap timeout, clean cache before client launch

* tor: post request timeout

* fix: post timeout

* build: update deps after merge

* tor: store arti runtime

* tor: do not send over tor if `manual` arg presents or `skip_send_attempt` set at config

* fix: arg name

* tor: handle arti runtime creation error

* tor: handle connection error

* tor: handle bootstrap error

* tor: handle start service name error

* tor: handle service config creation error

* tor: service proxy errors

* tor: handle service key creation emptiness

* build: format code

* build: update arti to 0.43, hyper to 0.10.1

* api: start foreign listener before tor connection

* tor: handle json parse errors

* tor: prevent to create several client runtimes, ability to recreate

* tor: return bootstrap error

* tor: handle host parse error

* tor: restart proxy on error

* tor: do not use integrated client when config value use_integrated is missing, add logging

* build: update lock file

* Global Tor client state (#762)

* tor: global client state

* tor: optimize init client thread-safety

* tor: handle config change on client init

* tor: add logging for client reuse or reinit

* tor: do not reuse arti client for requests

* Optimize tor sync flow (#763)

* Connection timeout (#765)

* Update deps (#768)

* build: update grin submodule to last staging

* build: update grin submodule

* build: remove remove_dir_all dependency

* build: update rpassword

* build: update semver

* build: remove unused deps

* build: update ring

* build: update lock file deps

* build: update rustyline

* build: update ed25519-dalek

* build: update curve25519-dalek

* build: update age

* build: update uuid

* fix: uuid test

* build: update x25519-dalek

* fix: x25519-dalek build

* build: update arti

* build: update grin submodule

* build: update hyper

* fix: initialize rustls provider for tests

* build: update grin submodule

* fix: rustls install provider

* tor: share getting private key

* fix: show an error on node version parse

* cli: renamed prompt password method

* fix: replace into_boxed_slice with try_from

* fix: dalek tests for onion

* config: comment expanded secret key

* fix: import api body for controller

* password: handle prompt error

* wallet: parse node error message

* tests: do not use random values for sign messages

* build: make hook executable

* build: cargo format all

* rustls: do not install provider at tests and globally

* build: update grin submodule

* build: fix api channel from grin submodule

* args: use read_password for piped prompt

* build: remove unused dep

* test: fixed signature

* preserve piped pw input

---------

Co-authored-by: wiesche <wiesche89@googlemail.com>

* Bump lodash from 4.17.21 to 4.18.1 (#774)

* build: update lodash to 4.18.1

* fix: readme

* docs: add owner api authentication setup

* build: update package-lock.json to version 3

* fix: token result, inline some vars

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* Global config instance (#769)

* config: global instance

* fix: cli tests

* fix: owner api tests

* config: save tor config

* fix: owner rpc tests

* fix: set config file path on init and owner api call

* tor: store launched services, get global config at command loop, remove unused listen args, check for empty global config to set default, do not save empty tor config at owner

* api: update config in memory after successful file write

* arti: restart proxy in loop

* fix: comment for tor config save

* config: set or init, update without error

* config: scoped tor config

* build: update lock file

* config: ability to store multiple configurations at memory from config path

* tor: restart service on config change

* fix: owner api test

* foreign: pass tor config from args, stop service, error handling

* arti: move runtime wrapper to single file

* config: read existing config from file at create_config

* config: handle error on read

* arti: single dir for cache

* foreign: register config listener before launch

* config: save temp

* config: remove unused error type

* config: make path and members not optional, return an error on config creation if it exists, pass default tor config to send if not set

* arti: non public runtime wrapper

* config: migrate comments

* fix: rpc tests

* config: return from cache if exists

* config: save disabled tor config when null provided at owner and tor section was not set

* config: update tor with args at listener

* config: pass pathbuf directly on creation

* config: unique tmp file name, setting permissions and providing config version

* fix global config handling

* fix config persistence

* fix tor service restart

* fix config synchronization

* require wallet close before changing data directory

* unify global config updates

---------

Co-authored-by: wiesche <wiesche89@googlemail.com>

* Wrong Slatepack address fix (#773)

* Use native tls for client (#779)

* client: use native tls and disable default features for reqwest

* build: bring back reqwest default features except tls

* client: remove tls selection

* expose mwixnet onion apis (#781)

* Update jayson and uuid (#777)

* build: update jayson and uuid

* npm: update lock file to v3

* npm: update lock file

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* Optimize outputs scan and selection (#780)

* Make updater APIs public (#782)

* Add mwixnet wallet request support

* mwixnet key conversion tests

* validate and track mwixnet requests

* fix Arti HTTP POST request formatting

* add mwixnet wallet CLI submission

* unlock mwixnet outputs when requests are not sent

* support automatic mwixnet output selection

* move mwixnet response parsing to libwallet

* limit mwixnet hops

* centralize grin workspace dependencies

* fix tx filter

* handle unavailable terminal colors

* reject invalid invoice locking

* clarify bip32 derivation paths

* restore derivation path comments

* tor: downgrade arti to 0.43

* owner: put active account on top of list

* account table layout

* fix: some typos, imports, unwraps and formatting

* tx: lock outputs before sending with tor

* accounts: display balances at CLI and from owner API when min confirmations are set

* unpack plain slatepacks without password (#805)

* unpack plain slatepacks without password

* cli: better open wallet handling on wallet subcommand

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* account: do not skip info from serialization, fix owner rpc test

* reject zero send amounts (#799)

* cli: fix short for min confirmations at accounts subcommand

* accounts: optimize accounts selection

* owner: document minimum_confirmations for accounts

* accounts: optimize selection

* preserve accounts api compatibi and clean up balances

* avoid empty wallet seeds (#801)

* fix empty wallet seeds

* mnemonic: return actual error with entropy size on recovering

* seed: extend mnemonic error description

* seed: clarify mnemonic errors

* seed: clarify mnemonic errors, fix missing phrase test

* Clean up seed handling add test

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* owner: use same wallet lock for selecting and locking outputs on send

* fix: do not lock for late lock

* cli: explain how to cancel

* fix: error message for offline address and integrated tor

* test: late lock for cli and owner api

* wallet: persistence for active account

* fix: owner_rpc test

* fix: lock wallet till lock outputs on send

* fix: update docs when to call tx_lock_outputs

* build: update grin submodule

* tests: get rid of owner_single_use to use correct config path

* test: parallel send attempts

* fix: cancel hint

* fix: late lock test refresh balance

* fix: set active account at single batch

* owner: document persistence of set_active_account

* cli: error when create and active args are present at account

* fix: keep display account type as str

* restore windows test fixes

* fix locking docs cancel hint and tests

* test cli send failure

* fix current account flag

* fix active account use

* test account persistence

* fix cli account selection

* fix: cmd tests

* fix: cmd test

* fix account test

* Show HTTP status when node requests fail (#820)

* ci: cargo clippy

* fix submodule checkout

* update grin for clippy fixes

* isolate tests

* fix cli test

* fix clippy warnings

* fix mwixnet output lookup

* build: update grin submodule

* git: add clippy to hook

* fix review nits

* fix checks

* mwixnet: use MwixnetServerPublicKey wrapper for hop

* build: update grin submodule

* build: clippy fixes

* mwixnet: rename dalek public key

* simplify mwixnet keys

* clarify mwixnet docs

* clarify arti usage

* simplify mwixnet tests

* tidy mwixnet code and docs

* skip spent outputs

* simplify mwixnet send

* drop host clone

* fix mwixnet selection and arti errors

* make mwixnet fee optional

* mwixnet: use fee at amount format, show min on error

* fix: fee per hop test

* fix: fee error text check

* tor: increase circuit timeout to 60

* fix mwixnet refresh and help

* build: update grin submodule and mwixnet tests

* cli: do not update wallet state on cancellation of tx after failed mwixnet request

* mwixnet: create separate owner api method to send request, do not cancel tx on failed mwixnet request

* fix mwixnet cli args and error messages

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-15 21:15:56 +02:00

1466 lines
39 KiB
Rust

// Copyright 2021 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.
/// Argument parsing and error handling for wallet commands
use crate::api::TLSConfig;
use crate::cli::command_loop;
use crate::config::GRIN_WALLET_DIR;
use crate::util::file::get_first_line;
use crate::util::secp::key::SecretKey;
use crate::util::{Mutex, ZeroingString};
use grin_core as core;
use grin_core::core::amount_to_hr_string;
use grin_keychain as keychain;
use grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE;
use grin_util::secp::pedersen::Commitment;
use grin_wallet_api::Owner;
use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig};
use grin_wallet_controller::command::GlobalArgs;
use grin_wallet_controller::{command, Error};
use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl};
use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey};
use grin_wallet_libwallet::slatepack::SlatepackAddressIndex;
use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor};
use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider};
use clap::ArgMatches;
use linefeed::terminal::Signal;
use linefeed::{Interface, ReadResult};
use rpassword;
use std::convert::TryFrom;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use uuid::Uuid;
// define what to do on argument error
macro_rules! arg_parse {
( $r:expr ) => {
match $r {
Ok(res) => res,
Err(e) => {
return Err(Error::ArgumentError(format!("{}", e)));
}
}
};
}
/// 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, thiserror::Error)]
pub enum ParseError {
#[error("Invalid Arguments: {0}")]
ArgumentError(String),
#[error("Parsing IO error: {0}")]
IOError(String),
#[error("Wallet configuration already exists: {0}")]
WalletExists(String),
#[error("User Cancelled")]
CancelledError,
}
impl From<std::io::Error> for ParseError {
fn from(e: std::io::Error) -> ParseError {
ParseError::IOError(format!("{}", e))
}
}
fn prompt_password_internal(prompt: &str) -> Result<ZeroingString, Error> {
print!("{}", prompt);
std::io::stdout().flush().unwrap();
let stdin = std::io::stdin();
let password = if stdin.is_terminal() {
rpassword::read_password()
} else {
rpassword::read_password_with_config(
rpassword::ConfigBuilder::new()
.input_reader(stdin)
.output_discard()
.build(),
)
}
.map_err(|e| Error::GenericError(format!("{}", e)))?;
Ok(ZeroingString::from(password))
}
pub fn prompt_password(password: &Option<ZeroingString>) -> Result<ZeroingString, Error> {
match password {
None => Ok(prompt_password_internal("Password: ")?),
Some(p) => Ok(p.clone()),
}
}
fn prompt_password_confirm() -> Result<ZeroingString, Error> {
let mut first = ZeroingString::from("first");
let mut second = ZeroingString::from("second");
while first != second {
first = prompt_password_internal("Password: ")?;
second = prompt_password_internal("Confirm Password: ")?;
}
Ok(first)
}
fn prompt_recovery_phrase<L, C, K>(
wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>,
) -> Result<ZeroingString, ParseError>
where
DefaultWalletImpl<C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
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) => {
let mut w_lock = wallet.lock();
let p = w_lock.lc_provider().unwrap();
if p.validate_mnemonic(ZeroingString::from(line.clone()))
.is_ok()
{
phrase = ZeroingString::from(line);
break;
} else {
println!();
println!("Recovery word phrase is invalid.");
println!();
interface.set_buffer(&line)?;
}
}
}
}
Ok(phrase)
}
fn prompt_slatepack() -> Result<String, ParseError> {
let interface = Arc::new(Interface::new("slatepack_input")?);
let mut message = String::from("");
interface.set_report_signal(Signal::Interrupt, true);
interface.set_prompt("")?;
loop {
println!("Please paste your encoded slatepack message:");
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 SlatepackArmor::decode(line.as_bytes()).is_ok() {
message = line;
break;
} else {
println!();
println!("Input is not a valid slatepack.");
println!();
interface.set_buffer(&line)?;
}
}
}
}
Ok(message)
}
fn prompt_pay_invoice(slate: &Slate, dest: &str) -> Result<bool, ParseError> {
let interface = Arc::new(Interface::new("pay")?);
let amount = amount_to_hr_string(slate.amount, false);
interface.set_report_signal(Signal::Interrupt, true);
interface.set_prompt(
"To proceed, type the exact amount of the invoice as displayed above (or Q/q to quit) > ",
)?;
println!();
println!(
"This command will pay the amount specified in the invoice using your wallet's funds."
);
println!("After you confirm, the following will occur: ");
println!();
println!(
"* {} of your wallet funds will be added to the transaction to pay this invoice.",
amount
);
if !dest.is_empty() {
println!("* The wallet will IMMEDIATELY attempt to send the resulting transaction to the wallet listening at: '{}'.", dest);
println!("* If other wallet is not listening, the resulting transaction will output as a slatepack which you can manually send back to the invoice creator.");
} else {
println!("* The resulting transaction will output as a slatepack which you can manually send back to the invoice creator.");
}
println!();
println!("Please review the above information carefully before proceeding");
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() {
"Q" | "q" => return Err(ParseError::CancelledError),
result => {
if result == amount {
return Ok(true);
} else {
println!("Please enter exact amount of the invoice as shown above or Q to quit");
println!();
}
}
}
}
}
}
}
// instantiate wallet (needed by most functions)
pub fn inst_wallet<L, C, K>(
config: WalletConfig,
node_client: C,
) -> Result<grin_wallet_libwallet::WalletHandle<'static, L, C, K>, ParseError>
where
DefaultWalletImpl<C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut wallet = Box::new(DefaultWalletImpl::<C>::new(node_client.clone()).unwrap())
as Box<dyn WalletInst<'static, L, C, K>>;
let lc = wallet.lc_provider().unwrap();
let _ = lc.set_top_level_directory(&config.data_file_dir);
Ok(Arc::new(Mutex::new(wallet)))
}
// 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 an optional value, throws error if value isn't provided
fn parse_optional(args: &ArgMatches, name: &str) -> Result<Option<String>, ParseError> {
if !args.is_present(name) {
return Ok(None);
}
let arg = args.value_of(name);
match arg {
Some(ar) => Ok(Some(ar.into())),
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))
}
}
}
// As above, but optional
fn parse_u64_or_none(arg: Option<&str>) -> Option<u64> {
arg?.parse().ok()
}
pub fn parse_global_args(
config: &WalletConfig,
args: &ArgMatches,
) -> Result<command::GlobalArgs, ParseError> {
let account = if args.subcommand_matches("account").is_some() {
None
} else {
parse_optional(args, "account")?
};
let mut show_spent = false;
if args.is_present("show_spent") {
show_spent = true;
}
let api_secret = get_first_line(config.api_secret_path.clone());
let node_api_secret = get_first_line(config.node_api_secret_path.clone());
let password = args.value_of("pass").map(ZeroingString::from);
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 = "Private key for certificate is not set".to_string();
return Err(ParseError::ArgumentError(msg));
}
};
Some(TLSConfig::new(file, key))
}
};
Ok(command::GlobalArgs {
account,
show_spent,
api_secret,
node_api_secret,
password,
tls_conf,
})
}
pub fn parse_init_args<L, C, K>(
wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>,
config: &WalletConfig,
g_args: &command::GlobalArgs,
args: &ArgMatches,
_test_mode: bool,
) -> Result<command::InitArgs, Error>
where
DefaultWalletImpl<C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
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(wallet).map_err(|e| Error::GenericError(e.to_string()))?)
}
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 = if let Some(p) = g_args.password.clone() {
p
} else {
prompt_password_confirm()?
};
Ok(command::InitArgs {
list_length,
password,
config: config.clone(),
recovery_phrase,
restore: false,
})
}
pub fn parse_recover_args(g_args: &command::GlobalArgs) -> Result<command::RecoverArgs, Error>
where
{
let passphrase = prompt_password(&g_args.password)?;
Ok(command::RecoverArgs { passphrase })
}
pub fn parse_owner_api_args(
config: &mut WalletConfig,
args: &ArgMatches,
) -> Result<(), ParseError> {
if let Some(port) = args.value_of("port") {
config.owner_api_listen_port = Some(port.parse().unwrap());
}
if args.is_present("run_foreign") {
config.owner_api_include_foreign = Some(true);
}
Ok(())
}
pub fn parse_scan_rewind_hash_args(
args: &ArgMatches,
) -> Result<command::ViewWalletScanArgs, ParseError> {
let rewind_hash = parse_required(args, "rewind_hash")?;
let start_height = parse_u64_or_none(args.value_of("start_height"));
let backwards_from_tip = parse_u64_or_none(args.value_of("backwards_from_tip"));
if backwards_from_tip.is_some() && start_height.is_some() {
let msg = "backwards_from tip and start_height cannot both be present".to_string();
return Err(ParseError::ArgumentError(msg));
}
Ok(command::ViewWalletScanArgs {
rewind_hash: rewind_hash.into(),
start_height,
backwards_from_tip,
})
}
pub fn parse_account_args(account_args: &ArgMatches) -> Result<command::AccountArgs, ParseError> {
let create = account_args.value_of("create").map(|s| s.to_owned());
let active = account_args.value_of("active").map(|s| s.to_owned());
if create.is_some() && active.is_some() {
let msg = "create and active cannot both be present".to_string();
return Err(ParseError::ArgumentError(msg));
}
// minimum_confirmations
let min_c = parse_required(account_args, "minimum_confirmations")?;
let min_c = parse_u64(min_c, "minimum_confirmations")?;
Ok(command::AccountArgs {
create,
minimum_confirmations: min_c,
active,
})
}
pub fn parse_send_args(args: &ArgMatches) -> Result<command::SendArgs, ParseError> {
// amount
let amount = parse_required(args, "amount")?;
let (amount, spend_max) = if amount.eq_ignore_ascii_case("max") {
(Ok(0), true)
} else {
(core::core::amount_from_hr_string(amount), false)
};
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));
}
};
let amount_includes_fee = args.is_present("amount_includes_fee") || spend_max;
// 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");
let late_lock = args.is_present("late_lock");
// dest
let dest = args.value_of("dest").map(|dest| dest.to_owned());
// 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");
// ttl_blocks
let ttl_blocks = parse_u64_or_none(args.value_of("ttl_blocks"));
// max_outputs
let max_outputs = 500;
// target slate version to create/send
let target_slate_version = {
match args.is_present("slate_version") {
true => {
let v = parse_required(args, "slate_version")?;
Some(parse_u64(v, "slate_version")? as u16)
}
false => None,
}
};
let payment_proof_address = {
if let Some(a) = dest.clone() {
match args.is_present("no_payment_proof") {
false => Some(a),
true => None,
}
} else {
if !estimate_selection_strategies {
println!("No recipient Slatepack address or provided address invalid. No payment proof will be requested.");
}
None
}
};
let outfile = parse_optional(args, "outfile")?;
let skip_tor = if args.is_present("manual") {
Some(true)
} else {
None
};
let bridge = args.value_of("bridge").map(|b| b.to_string());
let slatepack_qr = args.is_present("slatepack_qr");
let address_index = parse_address_index_arg(args)?;
Ok(command::SendArgs {
amount,
amount_includes_fee,
use_max_amount: spend_max,
minimum_confirmations: min_c,
selection_strategy: selection_strategy.to_owned(),
estimate_selection_strategies,
late_lock,
dest,
change_outputs,
fluff,
max_outputs,
payment_proof_address,
ttl_blocks,
target_slate_version,
outfile,
skip_tor,
bridge,
slatepack_qr,
address_index,
})
}
fn parse_address_index_arg(args: &ArgMatches) -> Result<Option<SlatepackAddressIndex>, ParseError> {
let address = if let Some(i) = parse_optional(args, "address_index")? {
let val = i.parse::<u32>();
match val {
Ok(v) => Some(
SlatepackAddressIndex(v)
.check()
.map_err(|e| ParseError::ArgumentError(e.to_string()))?,
),
Err(e) => {
let msg = format!("Could not parse address_index as a whole number. e={}", e);
return Err(ParseError::ArgumentError(msg));
}
}
} else {
None
};
Ok(address)
}
fn parse_mwixnet_output(output: &str) -> Result<command::MwixnetOutput, ParseError> {
if output.eq_ignore_ascii_case("max") {
Ok(command::MwixnetOutput::Max)
} else if output.len() == PEDERSEN_COMMITMENT_SIZE * 2 {
let commitment = grin_util::from_hex(output)
.map_err(|e| ParseError::ArgumentError(format!("Invalid output commitment: {}", e)))?;
Ok(command::MwixnetOutput::Commitment(Commitment::from_vec(
commitment,
)))
} else {
let amount = core::core::amount_from_hr_string(output).map_err(|e| {
ParseError::ArgumentError(format!(
"Output must be a commitment, an amount, or 'max': {}",
e
))
})?;
Ok(command::MwixnetOutput::MinimumAmount(amount))
}
}
pub fn parse_mwixnet_args(args: &ArgMatches) -> Result<command::MwixnetArgs, ParseError> {
let output = parse_mwixnet_output(parse_required(args, "output")?)?;
let server = parse_required(args, "server")?
.try_into()
.map_err(|e| ParseError::ArgumentError(format!("Invalid mwixnet server: {}", e)))?;
let server_keys = args
.values_of("key")
.ok_or_else(|| {
ParseError::ArgumentError("At least one server key is required".to_string())
})?
.map(|key| {
MwixnetServerPublicKey::from_hex(key).map_err(|e| {
ParseError::ArgumentError(format!("Invalid mwixnet server key: {}", e))
})
})
.collect::<Result<Vec<_>, _>>()?;
let fee_per_hop = args
.value_of("fee_per_hop")
.map(core::core::amount_from_hr_string)
.transpose()
.map_err(|e| ParseError::ArgumentError(format!("Invalid fee_per_hop: {}", e)))?;
let minimum_confirmations = parse_u64(
parse_required(args, "minimum_confirmations")?,
"minimum_confirmations",
)?;
Ok(command::MwixnetArgs {
server,
output,
minimum_confirmations,
params: MixnetReqCreationParams {
server_keys,
fee_per_hop,
},
})
}
pub fn parse_receive_args(args: &ArgMatches) -> Result<command::ReceiveArgs, ParseError> {
let input_file = parse_input_file_arg(args)?;
let mut input_slatepack_message = None;
if input_file.is_none() {
input_slatepack_message = Some(prompt_slatepack()?);
}
let outfile = parse_optional(args, "outfile")?;
let skip_tor = if args.is_present("manual") {
Some(true)
} else {
None
};
let bridge = parse_optional(args, "bridge")?;
let slatepack_qr = args.is_present("slatepack_qr");
Ok(command::ReceiveArgs {
input_file,
input_slatepack_message,
skip_tor,
outfile,
bridge,
slatepack_qr,
})
}
fn parse_input_file_arg(args: &ArgMatches) -> Result<Option<String>, ParseError> {
let input_file = match args.is_present("input") {
true => {
let file = args.value_of("input").unwrap().to_owned();
// validate input
if !Path::new(&file).is_file() {
let msg = format!("File {} not found.", file);
return Err(ParseError::ArgumentError(msg));
}
Some(file)
}
false => None,
};
Ok(input_file)
}
pub fn parse_unpack_args(args: &ArgMatches) -> Result<command::ReceiveArgs, ParseError> {
let input_file = parse_input_file_arg(args)?;
let mut input_slatepack_message = None;
if input_file.is_none() {
input_slatepack_message = Some(prompt_slatepack()?);
}
let outfile = parse_optional(args, "outfile")?;
let skip_tor = if args.is_present("manual") {
Some(true)
} else {
None
};
let bridge = parse_optional(args, "bridge")?;
let slatepack_qr = args.is_present("slatepack_qr");
Ok(command::ReceiveArgs {
input_file,
input_slatepack_message,
skip_tor,
outfile,
bridge,
slatepack_qr,
})
}
pub fn parse_finalize_args(args: &ArgMatches) -> Result<command::FinalizeArgs, ParseError> {
let fluff = args.is_present("fluff");
let nopost = args.is_present("nopost");
let input_file = parse_input_file_arg(args)?;
let mut input_slatepack_message = None;
if input_file.is_none() {
input_slatepack_message = Some(prompt_slatepack()?);
}
let outfile = parse_optional(args, "outfile")?;
let slatepack_qr = args.is_present("slatepack_qr");
Ok(command::FinalizeArgs {
input_file,
input_slatepack_message,
fluff,
nopost,
outfile,
slatepack_qr,
})
}
pub fn parse_issue_invoice_args(
args: &ArgMatches,
) -> Result<command::IssueInvoiceArgs, ParseError> {
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));
}
};
// target slate version to create
let target_slate_version = {
match args.is_present("slate_version") {
true => {
let v = parse_required(args, "slate_version")?;
Some(parse_u64(v, "slate_version")? as u16)
}
false => None,
}
};
// dest, for encryption
let dest = args.value_of("dest").map(|dest| dest.to_owned());
let outfile = parse_optional(args, "outfile")?;
let slatepack_qr = args.is_present("slatepack_qr");
let address_index = parse_address_index_arg(args)?;
Ok(command::IssueInvoiceArgs {
dest,
issue_args: IssueInvoiceTxArgs {
dest_acct_name: None,
amount,
target_slate_version,
address_index,
},
outfile,
slatepack_qr,
})
}
fn get_slate<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<&SecretKey>,
args: &ArgMatches,
) -> Result<(Slate, Option<SlatepackAddress>), Error>
where
L: WalletLCProvider<'static, C, K>,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let input_file = match args.is_present("input") {
true => {
let file = args.value_of("input").unwrap().to_owned();
// validate input
if !Path::new(&file).is_file() {
let msg = format!("File {} not found.", file);
return Err(Error::GenericError(msg));
}
Some(file)
}
false => None,
};
let mut input_slatepack_message = None;
if input_file.is_none() {
input_slatepack_message = Some(prompt_slatepack().map_err(|e| {
let msg = format!("{}", e);
Error::GenericError(msg)
})?)
}
command::parse_slatepack(
owner_api,
keychain_mask,
input_file,
input_slatepack_message,
)
}
pub fn parse_process_invoice_args(
args: &ArgMatches,
prompt: bool,
slate: Slate,
mut ret_address: Option<SlatepackAddress>,
) -> Result<command::ProcessInvoiceArgs, ParseError> {
// 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");
// ttl_blocks
let ttl_blocks = parse_u64_or_none(args.value_of("ttl_blocks"));
// max_outputs
let max_outputs = 500;
if prompt {
let dest = parse_optional(args, "dest")?;
let dest = match dest {
Some(dest) => {
ret_address = Some(SlatepackAddress::try_from(dest.as_str()).map_err(|e| {
ParseError::ArgumentError(format!("Can not parse destination address {}", e))
})?);
dest
}
None => match ret_address.clone() {
Some(a) => String::try_from(&a).unwrap(),
None => String::from(""),
},
};
// Now we need to prompt the user whether they want to do this,
prompt_pay_invoice(&slate, &dest)?;
}
let outfile = parse_optional(args, "outfile")?;
let skip_tor = if args.is_present("manual") {
Some(true)
} else {
None
};
let bridge = parse_optional(args, "bridge")?;
let slatepack_qr = args.is_present("slatepack_qr");
let ret_address = ret_address.map(|a| a.to_string());
Ok(command::ProcessInvoiceArgs {
minimum_confirmations: min_c,
selection_strategy: selection_strategy.to_owned(),
estimate_selection_strategies,
ret_address,
slate,
max_outputs,
ttl_blocks,
skip_tor,
outfile,
bridge,
slatepack_qr,
})
}
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_check_args(args: &ArgMatches) -> Result<command::CheckArgs, ParseError> {
let delete_unconfirmed = args.is_present("delete_unconfirmed");
let start_height = parse_u64_or_none(args.value_of("start_height"));
let backwards_from_tip = parse_u64_or_none(args.value_of("backwards_from_tip"));
if backwards_from_tip.is_some() && start_height.is_some() {
let msg = "backwards_from tip and start_height cannot both be present".to_string();
return Err(ParseError::ArgumentError(msg));
}
Ok(command::CheckArgs {
start_height,
backwards_from_tip,
delete_unconfirmed,
})
}
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),
};
let tx_slate_id = parse_tx_slate_id_arg(args)?;
if tx_id.is_some() && tx_slate_id.is_some() {
let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string();
return Err(ParseError::ArgumentError(msg));
}
let count = match args.value_of("count") {
None => None,
Some(c) => Some(parse_u64(c, "count")? as u32),
};
Ok(command::TxsArgs {
id: tx_id,
tx_slate_id,
count,
})
}
fn parse_tx_slate_id_arg(args: &ArgMatches) -> Result<Option<Uuid>, ParseError> {
let tx_slate_id = match args.value_of("txid") {
None => None,
Some(tx) => match tx.parse() {
Ok(t) => Some(t),
Err(e) => {
let msg = format!("Could not parse txid parameter. e={}", e);
return Err(ParseError::ArgumentError(msg));
}
},
};
Ok(tx_slate_id)
}
pub fn parse_post_args(args: &ArgMatches) -> Result<command::PostArgs, ParseError> {
let fluff = args.is_present("fluff");
let input_file = parse_input_file_arg(args)?;
let mut input_slatepack_message = None;
if input_file.is_none() {
input_slatepack_message = Some(prompt_slatepack()?);
}
Ok(command::PostArgs {
input_file,
input_slatepack_message,
fluff,
})
}
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 = args.value_of("dumpfile").map(|d| d.to_owned());
Ok(command::RepostArgs {
id: tx_id.unwrap(),
dump_file,
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 = "'id' (-i) or 'txid' (-t) argument is required.".to_string();
return Err(ParseError::ArgumentError(msg));
}
Ok(command::CancelArgs {
tx_id,
tx_slate_id,
tx_id_string: tx_id_string.to_owned(),
})
}
pub fn parse_export_proof_args(args: &ArgMatches) -> Result<command::ProofExportArgs, ParseError> {
let output_file = parse_required(args, "output")?;
let tx_id = match args.value_of("id") {
None => None,
Some(tx) => Some(parse_u64(tx, "id")? as u32),
};
let tx_slate_id = parse_tx_slate_id_arg(args)?;
if tx_id.is_some() && tx_slate_id.is_some() {
let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string();
return Err(ParseError::ArgumentError(msg));
}
if tx_id.is_none() && tx_slate_id.is_none() {
let msg = "Either 'id' (-i) or 'txid' (-t) must be provided.".to_string();
return Err(ParseError::ArgumentError(msg));
}
Ok(command::ProofExportArgs {
output_file: output_file.to_owned(),
id: tx_id,
tx_slate_id,
})
}
pub fn parse_verify_proof_args(args: &ArgMatches) -> Result<command::ProofVerifyArgs, ParseError> {
let input_file = parse_required(args, "input")?;
Ok(command::ProofVerifyArgs {
input_file: input_file.to_owned(),
})
}
pub fn wallet_command<C, F>(
wallet_args: &ArgMatches,
config: GlobalWalletConfig,
mut node_client: C,
test_mode: bool,
wallet_inst_cb: F,
) -> Result<String, Error>
where
C: NodeClient + 'static + Clone,
F: FnOnce(
grin_wallet_libwallet::WalletHandle<
'static,
DefaultLCProvider<C, keychain::ExtKeychain>,
C,
keychain::ExtKeychain,
>,
),
{
let mut wallet_config = config.members.wallet.clone();
if let Some(dir) = wallet_args.value_of("top_level_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());
// legacy hack to avoid the need for changes in existing grin-wallet.toml files
// remove `wallet_data` from end of path
// new lifecycle provider assumes grin_wallet.toml is in root of data directory
let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir);
if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) {
top_level_wallet_dir.pop();
wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into();
}
// Instantiate wallet (doesn't open the wallet)
let wallet =
inst_wallet::<DefaultLCProvider<C, keychain::ExtKeychain>, C, keychain::ExtKeychain>(
wallet_config.clone(),
node_client,
)
.unwrap_or_else(|e| {
println!("{}", e);
std::process::exit(1);
});
{
let mut wallet_lock = wallet.lock();
let lc = wallet_lock.lc_provider()?;
let _ = lc.set_top_level_directory(&wallet_config.data_file_dir);
}
// provide wallet instance back to the caller (handy for testing with
// local wallet proxy, etc.)
wallet_inst_cb(wallet.clone());
// don't open wallet for certain lifecycle commands
let keychain_mask = match wallet_args.subcommand() {
("init", Some(_)) => None,
("recover", _) => None,
("cli", _) => None,
("unpack", Some(args)) => {
let args = arg_parse!(parse_unpack_args(args));
let slatepack = command::read_slatepack(args)?;
let mask = if slatepack.mode == 1 {
open_wallet(&wallet, &global_wallet_args, wallet_args)?
} else {
None
};
command::unpack(wallet.clone(), mask.as_ref(), slatepack)?;
return Ok("unpack".to_string());
}
("owner_api", _) => {
// If wallet exists and password is present then open it. Otherwise, that's fine too.
let open = {
let mut wallet_lock = wallet.lock();
let lc = wallet_lock.lc_provider()?;
wallet_args.is_present("pass") && lc.wallet_exists(None)?
};
if open {
open_wallet(&wallet, &global_wallet_args, wallet_args)?
} else {
None
}
}
_ => open_wallet(&wallet, &global_wallet_args, wallet_args)?,
};
let res = match wallet_args.subcommand() {
("cli", Some(_)) => command_loop(
config,
wallet,
keychain_mask,
&global_wallet_args,
test_mode,
),
_ => {
let tor_config = config.tor_config();
let mut owner_api = Owner::new(wallet, None, config.config_file_path);
parse_and_execute(
&mut owner_api,
keychain_mask,
&wallet_config,
tor_config,
&global_wallet_args,
wallet_args,
test_mode,
false,
)
}
};
if let Err(e) = res {
Err(e)
} else {
Ok(wallet_args.subcommand().0.to_owned())
}
}
fn open_wallet<L, C, K>(
wallet: &grin_wallet_libwallet::WalletHandle<'static, L, C, K>,
global_wallet_args: &GlobalArgs,
wallet_args: &ArgMatches,
) -> Result<Option<SecretKey>, Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let mut wallet_lock = wallet.lock();
let lc = wallet_lock.lc_provider()?;
let mask = lc.open_wallet(
None,
prompt_password(&global_wallet_args.password)?,
false,
false,
)?;
if let Some(account) = wallet_args.value_of("account") {
let wallet_inst = lc.wallet_inst()?;
wallet_inst.set_account_by_name(account)?;
}
Ok(mask)
}
#[allow(clippy::too_many_arguments)]
pub fn parse_and_execute<L, C, K>(
owner_api: &mut Owner<L, C, K>,
keychain_mask: Option<SecretKey>,
wallet_config: &WalletConfig,
tor_config: TorConfig,
global_wallet_args: &command::GlobalArgs,
wallet_args: &ArgMatches,
test_mode: bool,
cli_mode: bool,
) -> Result<(), Error>
where
DefaultWalletImpl<C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let km = keychain_mask.as_ref();
if test_mode {
owner_api.doctest_mode = true;
owner_api.doctest_retain_tld = true;
}
match wallet_args.subcommand() {
("init", Some(args)) => {
let a = arg_parse!(parse_init_args(
owner_api.wallet_inst.clone(),
wallet_config,
global_wallet_args,
args,
test_mode,
));
command::init(owner_api, global_wallet_args, a, test_mode)
}
("recover", Some(_)) => {
let a = arg_parse!(parse_recover_args(global_wallet_args,));
command::recover(owner_api, a)
}
("listen", Some(args)) => {
let mut c = wallet_config.clone();
if let Some(port) = args.value_of("port") {
c.api_listen_port = port.parse().unwrap();
}
let bridge = args.value_of("bridge").map(|bridge| bridge.into());
let use_tor = if args.is_present("no_tor") {
Some(false)
} else {
None
};
command::listen(
owner_api,
Arc::new(Mutex::new(keychain_mask)),
c,
bridge,
use_tor,
&global_wallet_args.clone(),
cli_mode,
test_mode,
)
}
("owner_api", Some(args)) => {
let mut c = wallet_config.clone();
let mut g = global_wallet_args.clone();
g.tls_conf = None;
arg_parse!(parse_owner_api_args(&mut c, args));
command::owner_api(owner_api, keychain_mask, &c, &g, test_mode)
}
("web", Some(_)) => command::owner_api(
owner_api,
keychain_mask,
wallet_config,
global_wallet_args,
test_mode,
),
("rewind_hash", Some(_)) => command::rewind_hash(owner_api, km),
("scan_rewind_hash", Some(args)) => {
let a = arg_parse!(parse_scan_rewind_hash_args(args));
command::scan_rewind_hash(
owner_api,
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
}
("account", Some(args)) => {
let a = arg_parse!(parse_account_args(args));
command::account(owner_api, km, a)
}
("send", Some(args)) => {
let a = arg_parse!(parse_send_args(args));
command::send(
owner_api,
km,
a,
tor_config,
wallet_config.dark_background_color_scheme.unwrap_or(true),
test_mode,
)
}
("mwixnet", Some(args)) => {
let a = arg_parse!(parse_mwixnet_args(args));
command::mwixnet(owner_api, km, a)
}
("receive", Some(args)) => {
let a = arg_parse!(parse_receive_args(args));
command::receive(owner_api, km, a, tor_config, test_mode)
}
("unpack", Some(args)) => {
let a = arg_parse!(parse_unpack_args(args));
let slatepack = command::read_slatepack(a)?;
command::unpack(owner_api.wallet_inst.clone(), km, slatepack)
}
("finalize", Some(args)) => {
let a = arg_parse!(parse_finalize_args(args));
command::finalize(owner_api, km, a)
}
("invoice", Some(args)) => {
let a = arg_parse!(parse_issue_invoice_args(args));
command::issue_invoice_tx(owner_api, km, a)
}
("pay", Some(args)) => {
// get slate first
let (slate, address) = get_slate(owner_api, km, args)?;
let a = arg_parse!(parse_process_invoice_args(args, !test_mode, slate, address));
command::process_invoice(
owner_api,
km,
tor_config,
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
test_mode,
)
}
("info", Some(args)) => {
let a = arg_parse!(parse_info_args(args));
command::info(
owner_api,
km,
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
}
("outputs", Some(_)) => command::outputs(
owner_api,
km,
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(
owner_api,
km,
a,
wallet_config.dark_background_color_scheme.unwrap_or(true),
)
}
("post", Some(args)) => {
let a = arg_parse!(parse_post_args(args));
command::post(owner_api, km, a)
}
("repost", Some(args)) => {
let a = arg_parse!(parse_repost_args(args));
command::repost(owner_api, km, a)
}
("cancel", Some(args)) => {
let a = arg_parse!(parse_cancel_args(args));
command::cancel(owner_api, km, a)
}
("export_proof", Some(args)) => {
let a = arg_parse!(parse_export_proof_args(args));
command::proof_export(owner_api, km, a)
}
("verify_proof", Some(args)) => {
let a = arg_parse!(parse_verify_proof_args(args));
command::proof_verify(owner_api, km, a)
}
("address", Some(_)) => command::address(owner_api, km),
("scan", Some(args)) => {
let a = arg_parse!(parse_check_args(args));
command::scan(owner_api, km, a)
}
("open", Some(_)) => {
// for CLI mode only, should be handled externally
Ok(())
}
("close", Some(_)) => {
// for CLI mode only, should be handled externally
Ok(())
}
_ => {
let msg = "Unknown wallet command, use 'grin-wallet help' for details".to_string();
Err(Error::ArgumentError(msg))
}
}
}
#[cfg(test)]
mod mwixnet_tests {
use super::*;
#[test]
fn parses_mwixnet_optional_fee() {
let yaml = load_yaml!("../bin/grin-wallet.yml");
let args = vec![
"grin-wallet",
"mwixnet",
"max",
"--server",
"mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion",
"--key",
"24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a",
];
let matches = clap::App::from_yaml(yaml)
.get_matches_from_safe(args.clone())
.unwrap();
let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap();
assert_eq!(parsed.params.fee_per_hop, None);
let mut custom_args = args;
custom_args.extend(["--fee_per_hop", "0.0125"]);
let matches = clap::App::from_yaml(yaml)
.get_matches_from_safe(custom_args)
.unwrap();
let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap();
assert_eq!(parsed.params.fee_per_hop, Some(12_500_000));
}
#[test]
fn mwixnet_args() {
let yaml = load_yaml!("../bin/grin-wallet.yml");
let key = "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a";
for keys in [vec!["--key", key], vec!["--key", key, "--key", key]] {
let key_count = keys.len() / 2;
let mut args = vec![
"grin-wallet",
"mwixnet",
"--server",
"mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion",
];
args.extend(keys);
args.push("max");
let matches = clap::App::from_yaml(yaml)
.get_matches_from_safe(args)
.unwrap();
let parsed =
parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap();
assert!(matches!(parsed.output, command::MwixnetOutput::Max));
assert_eq!(parsed.params.server_keys.len(), key_count);
}
}
#[test]
fn parses_mwixnet_output_selection() {
assert!(matches!(
parse_mwixnet_output("max").unwrap(),
command::MwixnetOutput::Max
));
assert!(matches!(
parse_mwixnet_output("10").unwrap(),
command::MwixnetOutput::MinimumAmount(10_000_000_000)
));
assert!(matches!(
parse_mwixnet_output(&format!("08{}", "00".repeat(32))).unwrap(),
command::MwixnetOutput::Commitment(_)
));
}
}