Normalize line endings

This commit is contained in:
Anynomous
2025-09-18 14:51:29 +02:00
parent aed932726c
commit 86de7c6bcd
165 changed files with 0 additions and 53523 deletions
-166
View File
@@ -1,166 +0,0 @@
// 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.
//! Main for building the binary of a Grin Reference Wallet
#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
use crate::config::ConfigError;
use crate::core::global;
use crate::util::init_logger;
use clap::App;
use grin_core as core;
use grin_util as util;
use grin_wallet::cmd;
use grin_wallet_config as config;
use grin_wallet_impls::HTTPNodeClient;
use std::env;
use std::path::PathBuf;
use std::path::MAIN_SEPARATOR;
// include build information
pub mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
pub fn info_strings() -> (String, String) {
(
format!(
"This is Grin Wallet version {}{}, built for {} by {}.",
built_info::PKG_VERSION,
built_info::GIT_VERSION.map_or_else(|| "".to_owned(), |v| format!(" (git {})", v)),
built_info::TARGET,
built_info::RUSTC_VERSION,
)
.to_string(),
format!(
"Built with profile \"{}\", features \"{}\".",
built_info::PROFILE,
built_info::FEATURES_STR,
)
.to_string(),
)
}
// Helper fuction to format paths according to OS, avoids bugs on Linux
pub fn fmt_path(path: String) -> String {
let sep = &MAIN_SEPARATOR.to_string();
let path = path.replace("/", &sep).replace("\\", &sep);
path
}
fn log_build_info() {
let (basic_info, detailed_info) = info_strings();
info!("{}", basic_info);
debug!("{}", detailed_info);
}
fn main() {
let exit_code = real_main();
std::process::exit(exit_code);
}
fn real_main() -> i32 {
let yml = load_yaml!("grin-wallet.yml");
let args = App::from_yaml(yml)
.version(built_info::PKG_VERSION)
.get_matches();
let chain_type = if args.is_present("testnet") {
global::ChainTypes::Testnet
} else if args.is_present("usernet") {
global::ChainTypes::UserTesting
} else {
global::ChainTypes::Mainnet
};
let mut current_dir = None;
let mut create_path = false;
if args.is_present("top_level_dir") {
let res = args.value_of("top_level_dir");
match res {
Some(d) => {
let d = fmt_path(d.to_owned().to_string()); // Fix for fs to work with paths on Linux
current_dir = Some(PathBuf::from(d));
}
None => {
warn!("Argument --top_level_dir needs a value. Defaulting to current directory")
}
}
}
// special cases for certain lifecycle commands
match args.subcommand() {
("init", Some(init_args)) => {
if init_args.is_present("here") {
current_dir = Some(env::current_dir().unwrap_or_else(|e| {
panic!("Error creating config file: {}", e);
}));
}
create_path = true;
}
_ => {}
}
// Load relevant config, try and load a wallet config file
// Use defaults for configuration if config file not found anywhere
let mut config = match config::initial_setup_wallet(&chain_type, current_dir, create_path) {
Ok(c) => c,
Err(e) => match e {
ConfigError::PathNotFoundError(m) => {
println!("Wallet configuration not found at {}. (Run `grin-wallet init` to create a new wallet)", m);
return 0;
}
m => {
println!("Unable to load wallet configuration: {} (Run `grin-wallet init` to create a new wallet)", m);
return 0;
}
},
};
//config.members.as_mut().unwrap().wallet.chain_type = Some(chain_type);
// Load logging config
let mut l = config.members.as_mut().unwrap().logging.clone().unwrap();
// no logging to stdout if we're running cli
match args.subcommand() {
("cli", _) => l.log_to_stdout = true,
_ => {}
};
init_logger(Some(l), None);
info!(
"Using wallet configuration file at {}",
config.config_file_path.as_ref().unwrap().to_str().unwrap()
);
log_build_info();
global::init_global_chain_type(
config
.members
.as_ref()
.unwrap()
.wallet
.chain_type
.as_ref()
.unwrap()
.clone(),
);
global::init_global_accept_fee_base(config.members.as_ref().unwrap().wallet.accept_fee_base());
let wallet_config = config.clone().members.unwrap().wallet;
let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap();
cmd::wallet_command(&args, config, node_client)
}
-448
View File
@@ -1,448 +0,0 @@
name: grin-wallet
about: Reference Grin Wallet
author: The Grin Team
args:
- testnet:
help: Run grin against the Testnet (as opposed to mainnet)
long: testnet
takes_value: false
- usernet:
help: Run grin as a local-only network. Doesn't block peer connections but will not connect to any peer or seed
long: usernet
takes_value: false
- pass:
help: Wallet passphrase used to encrypt wallet seed
short: p
long: pass
takes_value: true
- account:
help: Wallet account to use for this operation
short: a
long: account
takes_value: true
default_value: default
- top_level_dir:
help: Top directory in which wallet files are stored (location of 'grin-wallet.toml')
short: t
long: top_level_dir
takes_value: true
- show_spent:
help: Show spent outputs on wallet output commands
short: s
long: show_spent
takes_value: false
- api_server_address:
help: Api address of running node on which to check inputs and post transactions
short: r
long: api_server_address
takes_value: true
subcommands:
- cli:
about: Start the wallet in interactive CLI mode (EXPERIMENTAL and UNDER DEVELOPMENT)
- account:
about: List wallet accounts or create a new account
args:
- create:
help: Create a new wallet account with provided name
short: c
long: create
takes_value: true
- rewind_hash:
about: Return the hash of the wallet root public key.
- scan_rewind_hash:
about: Scan the UTXO set and return the outputs and the total of grin owned by a view wallet rewind hash.
args:
- rewind_hash:
help: Rewind hash of the wallet to be scanned in order to retrieve all the outputs and balance.
index: 1
- start_height:
help: If given, the first block from which to start the scan (default 1)
short: h
long: start_height
takes_value: true
- backwards_from_tip:
help: If given, start scan b blocks back from the tip
short: b
long: backwards_from_tip,
takes_value: true
- listen:
about: Runs the wallet in listening mode waiting for transactions
args:
- port:
help: Port on which to run the wallet listener
short: l
long: port
takes_value: true
- no_tor:
help: Don't start Tor listener when starting HTTP listener
short: n
long: no_tor
takes_value: false
- bridge:
help: Enable bridge relay with TOR listener
short: g
long: bridge
takes_value: true
- owner_api:
about: Runs the wallet's local web API
args:
- port:
help: Port on which to run the wallet owner listener
short: l
long: port
takes_value: true
- run_foreign:
help: Also run the Foreign API
long: run_foreign
takes_value: false
- send:
about: Builds a transaction to send coins and sends to the recipient via the Slatepack workflow
args:
- amount:
help: Number of coins to send with optional fraction, e.g. 12.423. Keyword 'max' will send maximum amount.
index: 1
- minimum_confirmations:
help: Minimum number of confirmations required for an output to be spendable
short: c
long: min_conf
default_value: "10"
takes_value: true
- selection_strategy:
help: Coin/Output selection strategy.
short: s
long: selection
possible_values:
- all
- smallest
default_value: smallest
takes_value: true
- estimate_selection_strategies:
help: Estimates all possible Coin/Output selection strategies.
short: e
long: estimate-selection
- late_lock:
help: EXPERIMENTAL - Do not lock the coins immediately, instead only lock them during finalization.
short: l
long: late-lock
- change_outputs:
help: Number of change outputs to generate (mainly for testing)
short: o
long: change_outputs
default_value: "1"
takes_value: true
- dest:
help: Intended recipient's Slatepack Address (or http listener address (DEPRECATED))
short: d
long: dest
takes_value: true
- no_payment_proof:
help: Don't request a payment proof, even if the Recipient's Slatepack address is provided in the -dest argument
short: n
long: no_payment_proof
- fluff:
help: Fluff the transaction (ignore Dandelion relay protocol)
short: f
long: fluff
- stored_tx:
help: If present, use the previously stored Unconfirmed transaction with given id
short: t
long: stored_tx
takes_value: true
- ttl_blocks:
help: If present, the number of blocks from the current after which wallets should refuse to process transactions further
short: b
long: ttl_blocks
takes_value: true
- manual:
help: If present, don't attempt to send the resulting Slatepack via TOR
short: m
long: manual
- outfile:
help: If present, overrides the filename and location of the output Slatepack file.
short: u
long: outfile
takes_value: true
- bridge:
help: Enable tor bridge relay when sending via Slatepack workflow
short: g
long: bridge
takes_value: true
- slatepack_qr:
help: Show slatepack data as QR code
short: q
long: slatepack_qr
- amount_includes_fee:
help: Transaction amount includes transaction fee. Recipient will receive (amount - fee).
long: amount_includes_fee
- unpack:
about: Unpack and display an armored Slatepack Message, decrypting if possible
args:
- input:
help: File containing a Slatepack Message
short: i
long: input
takes_value: true
- receive:
about: Processes a Slatepack Message to accept a transfer from a sender
args:
- input:
help: File containing a Slatepack Message
short: i
long: input
takes_value: true
- manual:
help: If present, don't attempt to send the resulting Slatepack via TOR
short: m
long: manual
- outfile:
help: If present, overrides the filename and location of the output Slatepack file.
short: u
long: outfile
takes_value: true
- bridge:
help: Enable tor bridge relay when receiving via Slatepack workflow
short: g
long: bridge
takes_value: true
- slatepack_qr:
help: Show slatepack data as QR code
short: q
long: slatepack_qr
- finalize:
about: Processes a Slatepack Message to finalize a transfer.
args:
- input:
help: Partial transaction to process, expects the receiver's transaction file.
short: i
long: input
takes_value: true
- fluff:
help: Fluff the transaction (ignore Dandelion relay protocol)
short: f
long: fluff
- nopost:
help: Do not post the transaction.
short: n
long: nopost
- outfile:
help: If present, overrides the filename and location of the output Slatepack file.
short: u
long: outfile
takes_value: true
- slatepack_qr:
help: Show slatepack data as QR code
short: q
long: slatepack_qr
- invoice:
about: Initialize an invoice transaction, outputting a Slatepack Message with the result
args:
- amount:
help: Number of coins to invoice with optional fraction, e.g. 12.423
index: 1
- dest:
help: Intended recipient's Slatepack Address
short: d
long: dest
takes_value: true
- outfile:
help: If present, overrides the filename and location of the output Slatepack file.
short: u
long: outfile
takes_value: true
- slatepack_qr:
help: Show slatepack data as QR code
short: q
long: slatepack_qr
- pay:
about: Spend coins to pay the provided invoice transaction
args:
- minimum_confirmations:
help: Minimum number of confirmations required for an output to be spendable
short: c
long: min_conf
default_value: "10"
takes_value: true
- selection_strategy:
help: Coin/Output selection strategy.
short: s
long: selection
possible_values:
- all
- smallest
default_value: smallest
takes_value: true
- estimate_selection_strategies:
help: Estimates all possible Coin/Output selection strategies.
short: e
long: estimate-selection
- dest:
help: The Slatepack address of the invoicing party's wallet (will override the address contained in the Slatepack)
short: d
long: dest
takes_value: true
- input:
help: Incoming Slatepack Message to process
short: i
long: input
takes_value: true
- ttl_blocks:
help: If present, the number of blocks from the current after which wallets should refuse to process transactions further
short: b
long: ttl_blocks
takes_value: true
- manual:
help: If present, don't attempt to send the resulting Slatepack via TOR
short: m
long: manual
- outfile:
help: If present, overrides the filename and location of the output Slatepack file.
short: u
long: outfile
takes_value: true
- bridge:
help: Enable tor bridge relay when paying invoice.
short: g
long: bridge
takes_value: true
- slatepack_qr:
help: Show slatepack data as QR code
short: q
long: slatepack_qr
- outputs:
about: Raw wallet output info (list of outputs)
- txs:
about: Display transaction information
args:
- id:
help: If specified, display transaction with given Id and all associated Inputs/Outputs
short: i
long: id
takes_value: true
- txid:
help: If specified, display transaction with given TxID UUID and all associated Inputs/Outputs
short: t
long: txid
takes_value: true
- count:
help: Maximum number of transactions to show
short: c
long: count
takes_value: true
- post:
about: Posts a finalized transaction to the chain
args:
- input:
help: File name of the transaction to post
short: i
long: input
takes_value: true
- fluff:
help: Fluff the transaction (ignore Dandelion relay protocol)
short: f
long: fluff
- repost:
about: Reposts a stored, completed but unconfirmed transaction to the chain, or dumps it to a file
args:
- id:
help: Transaction ID containing the stored completed transaction
short: i
long: id
takes_value: true
- dumpfile:
help: File name to duMp the transaction to instead of posting
short: m
long: dumpfile
takes_value: true
- fluff:
help: Fluff the transaction (ignore Dandelion relay protocol)
short: f
long: fluff
- cancel:
about: Cancels a previously created transaction, freeing previously locked outputs for use again
args:
- id:
help: The ID of the transaction to cancel
short: i
long: id
takes_value: true
- txid:
help: The TxID UUID of the transaction to cancel
short: t
long: txid
takes_value: true
- info:
about: Basic wallet contents summary
args:
- minimum_confirmations:
help: Minimum number of confirmations required for an output to be spendable
short: c
long: min_conf
default_value: "10"
takes_value: true
- init:
about: Initialize a new wallet seed file and database
args:
- here:
help: Create wallet files in the current directory instead of the default ~/.grin directory
short: h
long: here
takes_value: false
- short_wordlist:
help: Generate a 12-word recovery phrase/seed instead of default 24
short: s
long: short_wordlist
takes_value: false
- recover:
help: Initialize new wallet using a recovery phrase
short: r
long: recover
takes_value: false
- open:
about: Opens a wallet (interactive mode only)
- close:
about: Closes the wallet (interactive mode only)
- recover:
about: Displays a recovery phrase for the wallet. (use `init -r` to perform recovery)
- address:
about: Display the wallet's Slatepack address
- scan:
about: Checks a wallet's outputs against a live node, repairing and restoring missing outputs if required
args:
- delete_unconfirmed:
help: Delete any unconfirmed outputsm unlock any locked outputs and delete associated transactions while doing the check.
short: d
long: delete_unconfirmed
takes_value: false
- start_height:
help: If given, the first block from which to start the scan (default 1)
short: h
long: start_height
takes_value: true
- backwards_from_tip:
help: If given, start scan b blocks back from the tip
short: b
long: backwards_from_tip,
takes_value: true
- export_proof:
about: Export a payment proof from a completed transaction
args:
- output:
help: Output proof file
index: 1
- id:
help: If specified, retrieve the proof for the given transaction ID
short: i
long: id
takes_value: true
- txid:
help: If specified, retrieve the proof for the given Slate ID
short: t
long: txid
takes_value: true
- verify_proof:
about: Verify a payment proof
args:
- input:
help: Filename of a proof file
index: 1
-48
View File
@@ -1,48 +0,0 @@
// 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.
//! Build hooks to spit out version+build time info
use built;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
// Setting up git hooks in the project: rustfmt and so on.
let git_hooks = format!(
"git config core.hooksPath {}",
PathBuf::from("./.hooks").to_str().unwrap()
);
if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", &git_hooks])
.output()
.expect("failed to execute git config for hooks");
} else {
Command::new("sh")
.args(&["-c", &git_hooks])
.output()
.expect("failed to execute git config for hooks");
}
// build and versioning information
let out_dir_path = format!("{}{}", env::var("OUT_DIR").unwrap(), "/built.rs");
// don't fail the build if something's missing, may just be cargo release
let _ = built::write_built_file_with_opts(
Some(Path::new(env!("CARGO_MANIFEST_DIR"))),
Path::new(&out_dir_path),
);
}
-312
View File
@@ -1,312 +0,0 @@
// 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.
use crate::cmd::wallet_args;
use crate::util::secp::key::SecretKey;
use crate::util::Mutex;
use clap::App;
//use colored::Colorize;
use grin_keychain as keychain;
use grin_wallet_api::Owner;
use grin_wallet_config::{TorConfig, WalletConfig};
use grin_wallet_controller::command::GlobalArgs;
use grin_wallet_controller::Error;
use grin_wallet_impls::DefaultWalletImpl;
use grin_wallet_libwallet::{NodeClient, StatusMessage, WalletInst, WalletLCProvider};
use rustyline::completion::{Completer, FilenameCompleter, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{CompletionType, Config, Context, EditMode, Editor, Helper, OutputStreamType};
use std::borrow::Cow::{self, Borrowed, Owned};
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
const COLORED_PROMPT: &'static str = "\x1b[36mgrin-wallet>\x1b[0m ";
const PROMPT: &'static str = "grin-wallet> ";
//const HISTORY_PATH: &str = ".history";
// static for keeping track of current stdin buffer contents
lazy_static! {
static ref STDIN_CONTENTS: Mutex<String> = Mutex::new(String::from(""));
}
#[macro_export]
macro_rules! cli_message_inline {
($fmt_string:expr, $( $arg:expr ),+) => {
{
use std::io::Write;
let contents = STDIN_CONTENTS.lock();
/* use crate::common::{is_cli, COLORED_PROMPT}; */
/* if is_cli() { */
print!("\r");
print!($fmt_string, $( $arg ),*);
print!(" {}", COLORED_PROMPT);
print!("\x1B[J");
print!("{}", *contents);
std::io::stdout().flush().unwrap();
/*} else {
info!($fmt_string, $( $arg ),*);
}*/
}
};
}
#[macro_export]
macro_rules! cli_message {
($fmt_string:expr, $( $arg:expr ),+) => {
{
use std::io::Write;
/* use crate::common::{is_cli, COLORED_PROMPT}; */
/* if is_cli() { */
//print!("\r");
print!($fmt_string, $( $arg ),*);
println!();
std::io::stdout().flush().unwrap();
/*} else {
info!($fmt_string, $( $arg ),*);
}*/
}
};
}
/// function to catch updates
pub fn start_updater_thread(rx: Receiver<StatusMessage>) -> Result<(), Error> {
let _ = thread::Builder::new()
.name("wallet-updater-status".to_string())
.spawn(move || loop {
while let Ok(m) = rx.recv() {
match m {
StatusMessage::UpdatingOutputs(s) => cli_message_inline!("{}", s),
StatusMessage::UpdatingTransactions(s) => cli_message_inline!("{}", s),
StatusMessage::FullScanWarn(s) => cli_message_inline!("{}", s),
StatusMessage::Scanning(_, m) => {
//debug!("{}", s);
cli_message_inline!("Scanning - {}% complete - Please Wait", m);
}
StatusMessage::ScanningComplete(s) => cli_message_inline!("{}", s),
StatusMessage::UpdateWarning(s) => cli_message_inline!("{}", s),
}
}
});
Ok(())
}
pub fn command_loop<L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
keychain_mask: Option<SecretKey>,
wallet_config: &WalletConfig,
tor_config: &TorConfig,
global_wallet_args: &GlobalArgs,
test_mode: bool,
) -> Result<(), Error>
where
DefaultWalletImpl<'static, C>: WalletInst<'static, L, C, K>,
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: keychain::Keychain + 'static,
{
let editor = Config::builder()
.history_ignore_space(true)
.completion_type(CompletionType::List)
.edit_mode(EditMode::Emacs)
.output_stream(OutputStreamType::Stdout)
.build();
let mut reader = Editor::with_config(editor);
reader.set_helper(Some(EditorHelper(
FilenameCompleter::new(),
MatchingBracketHighlighter::new(),
)));
/*let history_file = self
.api
.config()
.get_data_path()
.unwrap()
.parent()
.unwrap()
.join(HISTORY_PATH);
if history_file.exists() {
let _ = reader.load_history(&history_file);
}*/
let yml = load_yaml!("../bin/grin-wallet.yml");
let mut app = App::from_yaml(yml).version(crate_version!());
let mut keychain_mask = keychain_mask;
// catch updater messages
let (tx, rx) = channel();
let mut owner_api = Owner::new(wallet_inst, Some(tx));
start_updater_thread(rx)?;
// start the automatic updater
owner_api.start_updater((&keychain_mask).as_ref(), Duration::from_secs(30))?;
let mut wallet_opened = false;
loop {
match reader.readline(PROMPT) {
Ok(command) => {
if command.is_empty() {
continue;
}
// TODO tidy up a bit
if command.to_lowercase() == "exit" {
break;
}
/* use crate::common::{is_cli, COLORED_PROMPT}; */
// reset buffer
{
let mut contents = STDIN_CONTENTS.lock();
*contents = String::from("");
}
// Just add 'grin-wallet' to each command behind the scenes
// so we don't need to maintain a separate definition file
let augmented_command = format!("grin-wallet {}", command);
let args =
app.get_matches_from_safe_borrow(augmented_command.trim().split_whitespace());
let done = match args {
Ok(args) => {
// handle opening /closing separately
keychain_mask = match args.subcommand() {
("open", Some(_)) => {
let mut wallet_lock = owner_api.wallet_inst.lock();
let lc = wallet_lock.lc_provider().unwrap();
let mask = match lc.open_wallet(
None,
wallet_args::prompt_password(&global_wallet_args.password),
false,
false,
) {
Ok(m) => {
wallet_opened = true;
m
}
Err(e) => {
cli_message!("{}", e);
None
}
};
if let Some(account) = args.value_of("account") {
if wallet_opened {
let wallet_inst = lc.wallet_inst()?;
wallet_inst.set_parent_key_id_by_name(account)?;
}
}
mask
}
("close", Some(_)) => {
let mut wallet_lock = owner_api.wallet_inst.lock();
let lc = wallet_lock.lc_provider().unwrap();
lc.close_wallet(None)?;
None
}
_ => keychain_mask,
};
match wallet_args::parse_and_execute(
&mut owner_api,
keychain_mask.clone(),
&wallet_config,
&tor_config,
&global_wallet_args,
&args,
test_mode,
true,
) {
Ok(_) => {
cli_message!("Command '{}' completed", args.subcommand().0);
false
}
Err(err) => {
cli_message!("{}", err);
false
}
}
}
Err(err) => {
cli_message!("{}", err);
false
}
};
reader.add_history_entry(command);
if done {
println!();
break;
}
}
Err(err) => {
println!("Unable to read line: {}", err);
break;
}
}
}
Ok(())
//let _ = reader.save_history(&history_file);
}
struct EditorHelper(FilenameCompleter, MatchingBracketHighlighter);
impl Completer for EditorHelper {
type Candidate = Pair;
fn complete(
&self,
line: &str,
pos: usize,
ctx: &Context<'_>,
) -> std::result::Result<(usize, Vec<Pair>), ReadlineError> {
self.0.complete(line, pos, ctx)
}
}
impl Hinter for EditorHelper {
fn hint(&self, line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<String> {
let mut contents = STDIN_CONTENTS.lock();
*contents = line.into();
None
}
}
impl Highlighter for EditorHelper {
fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {
self.1.highlight(line, pos)
}
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
default: bool,
) -> Cow<'b, str> {
if default {
Borrowed(COLORED_PROMPT)
} else {
Borrowed(prompt)
}
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned("\x1b[1m".to_owned() + hint + "\x1b[m")
}
fn highlight_char(&self, line: &str, pos: usize) -> bool {
self.1.highlight_char(line, pos)
}
}
impl Validator for EditorHelper {}
impl Helper for EditorHelper {}
-17
View File
@@ -1,17 +0,0 @@
// 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.
mod cli;
pub use cli::command_loop;
-18
View File
@@ -1,18 +0,0 @@
// 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.
mod wallet;
pub mod wallet_args;
pub use self::wallet::wallet_command;
-78
View File
@@ -1,78 +0,0 @@
// 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.
use crate::cmd::wallet_args;
use crate::config::GlobalWalletConfig;
use clap::ArgMatches;
use grin_wallet_libwallet::NodeClient;
use semver::Version;
use std::thread;
use std::time::Duration;
const MIN_COMPAT_NODE_VERSION: &str = "4.0.0-alpha.1";
pub fn wallet_command<C>(
wallet_args: &ArgMatches<'_>,
config: GlobalWalletConfig,
mut node_client: C,
) -> i32
where
C: NodeClient + 'static,
{
// just get defaults from the global config
let wallet_config = config.members.clone().unwrap().wallet;
let tor_config = config.members.unwrap().tor;
// Check the node version info, and exit with report if we're not compatible
let global_wallet_args = wallet_args::parse_global_args(&wallet_config, &wallet_args)
.expect("Can't read configuration file");
node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone());
// This will also cache the node version info for calls to foreign API check middleware
if let Some(v) = node_client.clone().get_version_info() {
if Version::parse(&v.node_version) < Version::parse(MIN_COMPAT_NODE_VERSION) {
println!("The Grin Node in use (version {}) is outdated and incompatible with this wallet version.", v.node_version);
println!(
"Please update the node to version {} or later and try again.",
MIN_COMPAT_NODE_VERSION
);
return 1;
}
}
// ... if node isn't available, allow offline functions
let res = wallet_args::wallet_command(
wallet_args,
wallet_config,
tor_config,
node_client,
false,
|_| {},
);
// we need to give log output a chance to catch up before exiting
thread::sleep(Duration::from_millis(100));
if let Err(e) = res {
println!("Wallet command failed: {}", e);
1
} else {
println!(
"Command '{}' completed successfully",
wallet_args.subcommand().0
);
0
}
}
File diff suppressed because it is too large Load Diff
-24
View File
@@ -1,24 +0,0 @@
// 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.
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate clap;
use grin_api as api;
use grin_util as util;
use grin_wallet_config as config;
mod cli;
pub mod cmd;