Less cloning and additional pattern simplifications (#326)

* API cleanup

* Config cleanup

* Impl cleanup

* Libwallet cleanup

* Additionnal simplification
This commit is contained in:
Quentin Le Sceller
2020-02-07 09:39:56 +00:00
committed by GitHub
parent 2d264db91a
commit 1116bc5545
35 changed files with 554 additions and 616 deletions
+11 -12
View File
@@ -25,7 +25,7 @@ use std::path::MAIN_SEPARATOR;
use crate::tor::config as tor_config;
use crate::tor::process as tor_process;
const TOR_CONFIG_PATH: &'static str = "tor/sender";
const TOR_CONFIG_PATH: &str = "tor/sender";
#[derive(Clone)]
pub struct HttpSlateSender {
@@ -78,10 +78,9 @@ impl HttpSlateSender {
let err_string = format!("{}", e);
if err_string.contains("404") {
// Report that the other version of the wallet is out of date
report = format!(
"Other wallet is incompatible and requires an upgrade. \
report = "Other wallet is incompatible and requires an upgrade. \
Please urge the other wallet owner to upgrade and try the transaction again."
);
.to_string();
}
error!("{}", report);
ErrorKind::ClientCallback(report)
@@ -107,7 +106,7 @@ impl HttpSlateSender {
// trivial tests for now, but will be expanded later
if foreign_api_version < 2 {
let report = format!("Other wallet reports unrecognized API format.");
let report = "Other wallet reports unrecognized API format.".to_string();
error!("{}", report);
return Err(ErrorKind::ClientCallback(report).into());
}
@@ -119,7 +118,7 @@ impl HttpSlateSender {
return Ok(SlateVersion::V2);
}
let report = format!("Unable to negotiate slate format with other wallet.");
let report = "Unable to negotiate slate format with other wallet.".to_string();
error!("{}", report);
Err(ErrorKind::ClientCallback(report).into())
}
@@ -136,7 +135,7 @@ impl HttpSlateSender {
let mut client = Client::new();
if self.use_socks {
client.use_socks = true;
client.socks_proxy_addr = self.socks_proxy_addr.clone();
client.socks_proxy_addr = self.socks_proxy_addr;
}
let req = client.create_post_request(url, api_secret, &input)?;
let res = client.send_request(req)?;
@@ -167,24 +166,24 @@ impl SlateSender for HttpSlateSender {
&tor_dir,
&self.socks_proxy_addr.unwrap().to_string(),
)
.map_err(|e| ErrorKind::TorConfig(format!("{:?}", e).into()))?;
.map_err(|e| ErrorKind::TorConfig(format!("{:?}", e)))?;
// Start TOR process
tor.torrc_path(&format!("{}/torrc", &tor_dir))
.working_dir(&tor_dir)
.timeout(20)
.completion_percent(100)
.launch()
.map_err(|e| ErrorKind::TorProcess(format!("{:?}", e).into()))?;
.map_err(|e| ErrorKind::TorProcess(format!("{:?}", e)))?;
}
let slate_send = match self.check_other_version(&url_str)? {
SlateVersion::V3 => VersionedSlate::into_version(slate.clone(), SlateVersion::V3),
SlateVersion::V2 => {
let mut slate = slate.clone();
if let Some(_) = slate.payment_proof {
if slate.payment_proof.is_some() {
return Err(ErrorKind::ClientCallback("Payment proof requested, but other wallet does not support payment proofs. Please urge other user to upgrade, or re-send tx without a payment proof".into()).into());
}
if let Some(_) = slate.ttl_cutoff_height {
if slate.ttl_cutoff_height.is_some() {
warn!("Slate TTL value will be ignored and removed by other wallet, as other wallet does not support this feature. Please urge other user to upgrade");
}
slate.version_info.version = 2;
@@ -236,7 +235,7 @@ pub struct SchemeNotHttp;
impl Into<Error> for SchemeNotHttp {
fn into(self) -> Error {
let err_str = format!("url scheme must be http",);
let err_str = "url scheme must be http".to_string();
ErrorKind::GenericError(err_str).into()
}
}
+35 -47
View File
@@ -44,7 +44,7 @@ impl KeybaseChannel {
/// Check if keybase is installed and return an adapter object.
pub fn new(channel: String) -> Result<KeybaseChannel, Error> {
// Limit only one recipient
if channel.matches(",").count() > 0 {
if channel.matches(',').count() > 0 {
return Err(
ErrorKind::GenericError("Only one recipient is supported!".to_owned()).into(),
);
@@ -83,12 +83,12 @@ fn api_send(payload: &str) -> Result<Value, Error> {
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
Err(ErrorKind::GenericError("keybase api fail".to_owned()).into())
} else {
let response: Value =
from_str(from_utf8(&output.stdout).expect("Bad output")).expect("Bad output");
let err_msg = format!("{}", response["error"]["message"]);
if err_msg.len() > 0 && err_msg != "null" {
if !err_msg.is_empty() && err_msg != "null" {
error!("api_send got error: {}", err_msg);
}
@@ -107,12 +107,12 @@ fn whoami() -> Result<String, Error> {
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
Err(ErrorKind::GenericError("keybase api fail".to_owned()).into())
} else {
let response: Value =
from_str(from_utf8(&output.stdout).expect("Bad output")).expect("Bad output");
let err_msg = format!("{}", response["error"]["message"]);
if err_msg.len() > 0 && err_msg != "null" {
if !err_msg.is_empty() && err_msg != "null" {
error!("status query got error: {}", err_msg);
}
@@ -121,9 +121,7 @@ fn whoami() -> Result<String, Error> {
Ok(s.to_string())
} else {
error!("keybase username query fail");
Err(ErrorKind::GenericError(
"keybase username query fail".to_owned(),
))?
Err(ErrorKind::GenericError("keybase username query fail".to_owned()).into())
}
}
}
@@ -159,7 +157,7 @@ fn read_from_channel(channel: &str, topic: &str) -> Result<Vec<String>, Error> {
}
Ok(unread)
} else {
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
Err(ErrorKind::GenericError("keybase api fail".to_owned()).into())
}
}
@@ -202,7 +200,7 @@ fn get_unread(topic: &str) -> Result<HashMap<String, String>, Error> {
}
Ok(unread)
} else {
Err(ErrorKind::GenericError("keybase api fail".to_owned()))?
Err(ErrorKind::GenericError("keybase api fail".to_owned()).into())
}
}
@@ -276,16 +274,11 @@ fn poll(nseconds: u64, channel: &str) -> Option<Slate> {
let unread = read_from_channel(channel, SLATE_SIGNED);
for msg in unread.unwrap().iter() {
let blob = Slate::deserialize_upgrade(&msg);
match blob {
Ok(slate) => {
let slate: Slate = slate.into();
info!(
"keybase response message received from @{}, tx uuid: {}",
channel, slate.id,
);
return Some(slate);
}
Err(_) => (),
if let Ok(slate) = blob {
info!(
"keybase response message received from @{}, tx uuid: {}",
channel, slate.id,
);
}
}
sleep(POLL_SLEEP_DURATION);
@@ -306,19 +299,17 @@ impl SlateSender for KeybaseChannel {
match send(&slate, &self.0, SLATE_NEW, TTL) {
true => (),
false => {
return Err(ErrorKind::ClientCallback(
"Posting transaction slate".to_owned(),
))?;
return Err(
ErrorKind::ClientCallback("Posting transaction slate".to_owned()).into(),
);
}
}
info!("tx request has been sent to @{}, tx uuid: {}", &self.0, id);
// Wait for response from recipient with SLATE_SIGNED topic
match poll(TTL as u64, &self.0) {
Some(slate) => return Ok(slate),
Some(slate) => Ok(slate),
None => {
return Err(ErrorKind::ClientCallback(
"Receiving reply from recipient".to_owned(),
))?;
Err(ErrorKind::ClientCallback("Receiving reply from recipient".to_owned()).into())
}
}
}
@@ -355,17 +346,16 @@ impl SlateReceiver for KeybaseAllChannels {
node_api_secret: Option<String>,
) -> Result<(), Error> {
let node_client = HTTPNodeClient::new(&config.check_node_api_http_addr, node_api_secret);
let mut wallet = Box::new(
DefaultWalletImpl::<'static, HTTPNodeClient>::new(node_client.clone()).unwrap(),
)
as Box<
dyn WalletInst<
'static,
DefaultLCProvider<HTTPNodeClient, ExtKeychain>,
HTTPNodeClient,
ExtKeychain,
>,
>;
let mut wallet =
Box::new(DefaultWalletImpl::<'static, HTTPNodeClient>::new(node_client).unwrap())
as Box<
dyn WalletInst<
'static,
DefaultLCProvider<HTTPNodeClient, ExtKeychain>,
HTTPNodeClient,
ExtKeychain,
>,
>;
let lc = wallet.lc_provider().unwrap();
lc.set_top_level_directory(&config.data_file_dir)?;
let mask = lc.open_wallet(None, passphrase, true, false)?;
@@ -383,17 +373,16 @@ impl SlateReceiver for KeybaseAllChannels {
for (msg, channel) in &unread.unwrap() {
let blob = Slate::deserialize_upgrade(&msg);
match blob {
Ok(message) => {
let slate: Slate = message.clone().into();
Ok(slate) => {
let tx_uuid = slate.id;
// Reject multiple recipients channel for safety
{
if channel.matches(",").count() > 1 {
if channel.matches(',').count() > 1 {
error!(
"Incoming tx initiated on channel \"{}\" is rejected, multiple recipients channel! amount: {}(g), tx uuid: {}",
channel,
slate.amount as f64 / 1000000000.0,
slate.amount as f64 / 1_000_000_000.0,
tx_uuid,
);
continue;
@@ -403,7 +392,7 @@ impl SlateReceiver for KeybaseAllChannels {
info!(
"tx initiated on channel \"{}\", to send you {}(g). tx uuid: {}",
channel,
slate.amount as f64 / 1000000000.0,
slate.amount as f64 / 1_000_000_000.0,
tx_uuid,
);
if let Err(e) = slate.verify_messages() {
@@ -411,15 +400,14 @@ impl SlateReceiver for KeybaseAllChannels {
return Err(e);
}
let res = {
let r = foreign::receive_tx(
foreign::receive_tx(
&mut **wallet_inst,
Some(mask.as_ref().unwrap()),
&slate,
None,
None,
false,
);
r
)
};
match res {
// Reply to the same channel with topic SLATE_SIGNED
@@ -460,7 +448,7 @@ fn notify_on_receive(keybase_notify_ttl: u16, channel: String, tx_uuid: String)
if keybase_notify_ttl > 0 {
let my_username = whoami();
if let Ok(username) = my_username {
let split = channel.split(",");
let split = channel.split(',');
let vec: Vec<&str> = split.collect();
if vec.len() > 1 {
let receiver = username;
+2 -2
View File
@@ -70,7 +70,7 @@ pub fn create_sender(
))
};
let mut method = method.into();
let mut method = method;
// will test if this is a tor address and fill out
// the http://[].onion if missing
@@ -95,7 +95,7 @@ pub fn create_sender(
.map_err(|_| invalid())?,
),
},
"keybase" => Box::new(KeybaseChannel::new(dest.to_owned())?),
"keybase" => Box::new(KeybaseChannel::new(dest)?),
"self" => {
return Err(ErrorKind::WalletComms(
"No sender implementation for \"self\".".to_string(),
+21 -21
View File
@@ -41,19 +41,19 @@ use crate::util::{self, secp};
use rand::rngs::mock::StepRng;
use rand::thread_rng;
pub const DB_DIR: &'static str = "db";
pub const TX_SAVE_DIR: &'static str = "saved_txs";
pub const DB_DIR: &str = "db";
pub const TX_SAVE_DIR: &str = "saved_txs";
const OUTPUT_PREFIX: u8 = 'o' as u8;
const DERIV_PREFIX: u8 = 'd' as u8;
const CONFIRMED_HEIGHT_PREFIX: u8 = 'c' as u8;
const PRIVATE_TX_CONTEXT_PREFIX: u8 = 'p' as u8;
const TX_LOG_ENTRY_PREFIX: u8 = 't' as u8;
const TX_LOG_ID_PREFIX: u8 = 'i' as u8;
const ACCOUNT_PATH_MAPPING_PREFIX: u8 = 'a' as u8;
const LAST_SCANNED_BLOCK: u8 = 'l' as u8;
const OUTPUT_PREFIX: u8 = b'o';
const DERIV_PREFIX: u8 = b'd';
const CONFIRMED_HEIGHT_PREFIX: u8 = b'c';
const PRIVATE_TX_CONTEXT_PREFIX: u8 = b'p';
const TX_LOG_ENTRY_PREFIX: u8 = b't';
const TX_LOG_ID_PREFIX: u8 = b'i';
const ACCOUNT_PATH_MAPPING_PREFIX: u8 = b'a';
const LAST_SCANNED_BLOCK: u8 = b'l';
const LAST_SCANNED_KEY: &str = "LAST_SCANNED_KEY";
const WALLET_INIT_STATUS: u8 = 'w' as u8;
const WALLET_INIT_STATUS: u8 = b'w';
const WALLET_INIT_STATUS_KEY: &str = "WALLET_INIT_STATUS";
/// test to see if database files exist in the current directory. If so,
@@ -79,7 +79,7 @@ where
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
hasher.update(&root_key.0[..]);
hasher.update(&slate_id[..]);
hasher.update(&"blind".as_bytes()[..]);
hasher.update(&b"blind"[..]);
let blind_xor_key = hasher.finalize();
let mut ret_blind = [0; SECRET_KEY_SIZE];
ret_blind.copy_from_slice(&blind_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
@@ -88,7 +88,7 @@ where
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
hasher.update(&root_key.0[..]);
hasher.update(&slate_id[..]);
hasher.update(&"nonce".as_bytes()[..]);
hasher.update(&b"nonce"[..]);
let nonce_xor_key = hasher.finalize();
let mut ret_nonce = [0; SECRET_KEY_SIZE];
ret_nonce.copy_from_slice(&nonce_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
@@ -200,7 +200,7 @@ where
// before it is used
let mask_value = match use_test_rng {
true => {
let mut test_rng = StepRng::new(1234567890u64, 1);
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
secp::key::SecretKey::new(&k.secp(), &mut test_rng)
}
false => secp::key::SecretKey::new(&k.secp(), &mut thread_rng()),
@@ -280,7 +280,7 @@ where
self.set_parent_key_id(a.path);
Ok(())
} else {
return Err(ErrorKind::UnknownAccountLabel(label.clone()).into());
Err(ErrorKind::UnknownAccountLabel(label).into())
}
}
@@ -334,8 +334,8 @@ where
})?;
for i in 0..SECRET_KEY_SIZE {
ctx.sec_key.0[i] = ctx.sec_key.0[i] ^ blind_xor_key[i];
ctx.sec_nonce.0[i] = ctx.sec_nonce.0[i] ^ nonce_xor_key[i];
ctx.sec_key.0[i] ^= blind_xor_key[i];
ctx.sec_nonce.0[i] ^= nonce_xor_key[i];
}
Ok(ctx)
@@ -428,9 +428,9 @@ where
}
};
let mut return_path = self.parent_key_id.to_path();
return_path.depth = return_path.depth + 1;
return_path.depth += 1;
return_path.path[return_path.depth as usize - 1] = ChildNumber::from(deriv_idx);
deriv_idx = deriv_idx + 1;
deriv_idx += 1;
let mut batch = self.batch(keychain_mask)?;
batch.save_child_index(&parent_key_id, deriv_idx)?;
batch.commit()?;
@@ -696,8 +696,8 @@ where
let mut s_ctx = ctx.clone();
for i in 0..SECRET_KEY_SIZE {
s_ctx.sec_key.0[i] = s_ctx.sec_key.0[i] ^ blind_xor_key[i];
s_ctx.sec_nonce.0[i] = s_ctx.sec_nonce.0[i] ^ nonce_xor_key[i];
s_ctx.sec_key.0[i] ^= blind_xor_key[i];
s_ctx.sec_nonce.0[i] ^= nonce_xor_key[i];
}
self.db
+3 -3
View File
@@ -339,9 +339,9 @@ impl Client {
let addr = match self.socks_proxy_addr {
Some(a) => a,
None => {
return Box::new(result(Err(ErrorKind::RequestError(format!(
"Can't parse Socks proxy address"
))
return Box::new(result(Err(ErrorKind::RequestError(
"Can't parse Socks proxy address".to_string(),
)
.into())))
}
};
+2 -2
View File
@@ -125,7 +125,7 @@ fn answer_hello(
if response[0] == 5 && response[1] == 0 {
Box::new(ok(socket))
} else if response[0] == 5 && response[1] == 2 && creds.is_some() {
Box::new(auth_negotiation(socket, creds).and_then(|socket| ok(socket)))
Box::new(auth_negotiation(socket, creds).and_then(ok))
} else {
Box::new(
Err(Error::new(
@@ -159,7 +159,7 @@ fn write_addr(socket: TcpStream, req: Destination) -> HandshakeFuture<TcpStream>
};
let mut packet = Vec::new();
packet.write_all(&vec![5, 1, 0]).unwrap();
packet.write_all(&[5, 1, 0]).unwrap();
packet.write_u8(3).unwrap();
packet.write_u8(host.as_bytes().len() as u8).unwrap();
+2 -8
View File
@@ -109,13 +109,7 @@ impl Fail for Error {
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
}
}
Ok(r) => r == "1",
Err(_) => false,
};
let backtrace = match self.backtrace() {
@@ -124,7 +118,7 @@ impl Display for Error {
};
let inner_output = format!("{}", self.inner,);
let backtrace_output = format!("\nBacktrace: {}", backtrace);
let mut output = inner_output.clone();
let mut output = inner_output;
if show_bt {
output.push_str(&backtrace_output);
}
+11 -12
View File
@@ -82,21 +82,21 @@ where
let logging = match logging_config {
Some(l) => Some(l),
None => match default_config.members.as_ref() {
Some(m) => m.clone().logging.clone(),
Some(m) => m.clone().logging,
None => None,
},
};
let wallet = match wallet_config {
Some(w) => w,
None => match default_config.members.as_ref() {
Some(m) => m.clone().wallet.clone(),
Some(m) => m.clone().wallet,
None => WalletConfig::default(),
},
};
let tor = match tor_config {
Some(t) => Some(t),
None => match default_config.members.as_ref() {
Some(m) => m.clone().tor.clone(),
Some(m) => m.clone().tor,
None => Some(TorConfig::default()),
},
};
@@ -138,7 +138,7 @@ where
let mut abs_path = std::env::current_dir()?;
abs_path.push(self.data_dir.clone());
default_config.update_paths(&PathBuf::from(abs_path));
default_config.update_paths(&abs_path);
let res = default_config.write_to_file(config_file_name.to_str().unwrap());
if let Err(e) = res {
let msg = format!(
@@ -180,7 +180,7 @@ where
if !test_mode {
if let Ok(true) = exists {
let msg = format!("Wallet seed already exists at: {}", data_dir_name);
return Err(ErrorKind::WalletSeedExists(msg))?;
return Err(ErrorKind::WalletSeedExists(msg).into());
}
}
WalletSeed::init_file(
@@ -245,10 +245,9 @@ where
}
fn close_wallet(&mut self, _name: Option<&str>) -> Result<(), Error> {
match self.backend.as_mut() {
Some(b) => b.close()?,
None => {}
};
if let Some(b) = self.backend.as_mut() {
b.close()?
}
self.backend = None;
Ok(())
}
@@ -283,7 +282,7 @@ where
fn validate_mnemonic(&self, mnemonic: ZeroingString) -> Result<(), Error> {
match WalletSeed::from_mnemonic(mnemonic) {
Ok(_) => Ok(()),
Err(_) => Err(ErrorKind::GenericError("Validating mnemonic".into()))?,
Err(_) => Err(ErrorKind::GenericError("Validating mnemonic".into()).into()),
}
}
@@ -345,9 +344,9 @@ where
)?;
if orig_wallet_seed != new_wallet_seed {
let msg = format!(
let msg =
"New and Old wallet seeds are not equal on password change, not removing backups."
);
.to_string();
return Err(ErrorKind::Lifecycle(msg).into());
}
// Removin
+11 -12
View File
@@ -29,7 +29,7 @@ use crate::util;
use crate::{Error, ErrorKind};
use failure::ResultExt;
pub const SEED_FILE: &'static str = "wallet.seed";
pub const SEED_FILE: &str = "wallet.seed";
#[derive(Clone, Debug, PartialEq)]
pub struct WalletSeed(Vec<u8>);
@@ -108,10 +108,8 @@ impl WalletSeed {
i += 1;
}
path.push(backup_seed_file_name.clone());
if let Err(_) = fs::rename(seed_file_name, backup_seed_file_name.as_str()) {
return Err(ErrorKind::GenericError(
"Can't rename wallet seed file".to_owned(),
))?;
if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() {
return Err(ErrorKind::GenericError("Can't rename wallet seed file".to_owned()).into());
}
warn!("{} backed up as {}", seed_file_name, backup_seed_file_name);
Ok(backup_seed_file_name)
@@ -133,7 +131,8 @@ impl WalletSeed {
data_file_dir.to_owned(),
"To create a new wallet from a recovery phrase, use 'grin-wallet init -r'"
.to_owned(),
))?;
)
.into());
}
let seed = WalletSeed::from_mnemonic(word_list)?;
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
@@ -162,7 +161,7 @@ impl WalletSeed {
if exists && !test_mode {
let msg = format!("Wallet seed already exists at: {}", data_file_dir);
error!("{}", msg);
return Err(ErrorKind::WalletSeedExists(msg))?;
return Err(ErrorKind::WalletSeedExists(msg).into());
}
let seed = match recovery_phrase {
@@ -203,7 +202,7 @@ impl WalletSeed {
Run \"grin-wallet init\" to initialize a new wallet.",
seed_file_path
);
Err(ErrorKind::WalletSeedDoesntExist)?
Err(ErrorKind::WalletSeedDoesntExist.into())
}
}
@@ -242,7 +241,7 @@ impl EncryptedWalletSeed {
let mut key = [0; 32];
pbkdf2::derive(&digest::SHA512, 100, &salt, password, &mut key);
let content = seed.0.to_vec();
let mut enc_bytes = content.clone();
let mut enc_bytes = content;
let suffix_len = aead::CHACHA20_POLY1305.tag_len();
for _ in 0..suffix_len {
enc_bytes.push(0);
@@ -262,15 +261,15 @@ impl EncryptedWalletSeed {
pub fn decrypt(&self, password: &str) -> Result<WalletSeed, Error> {
let mut encrypted_seed = match util::from_hex(self.encrypted_seed.clone()) {
Ok(s) => s,
Err(_) => return Err(ErrorKind::Encryption)?,
Err(_) => return Err(ErrorKind::Encryption.into()),
};
let salt = match util::from_hex(self.salt.clone()) {
Ok(s) => s,
Err(_) => return Err(ErrorKind::Encryption)?,
Err(_) => return Err(ErrorKind::Encryption.into()),
};
let nonce = match util::from_hex(self.nonce.clone()) {
Ok(s) => s,
Err(_) => return Err(ErrorKind::Encryption)?,
Err(_) => return Err(ErrorKind::Encryption.into()),
};
let password = password.as_bytes();
let mut key = [0; 32];
+7 -9
View File
@@ -142,9 +142,7 @@ impl NodeClient for HTTPNodeClient {
) -> Result<Option<(TxKernel, u64, u64)>, libwallet::Error> {
let version = self
.get_version_info()
.ok_or(libwallet::ErrorKind::ClientCallback(
"Unable to get version".into(),
))?;
.ok_or_else(|| libwallet::ErrorKind::ClientCallback("Unable to get version".into()))?;
let version = Version::parse(&version.node_version)
.map_err(|_| libwallet::ErrorKind::ClientCallback("Unable to parse version".into()))?;
if version <= Version::new(2, 0, 0) {
@@ -159,12 +157,12 @@ impl NodeClient for HTTPNodeClient {
query += &format!("min_height={}", h);
}
if let Some(h) = max_height {
if query.len() > 0 {
if !query.is_empty() {
query += "&";
}
query += &format!("max_height={}", h);
}
if query.len() > 0 {
if !query.is_empty() {
query.insert_str(0, "?");
}
@@ -292,7 +290,7 @@ impl NodeClient for HTTPNodeClient {
out,
e);
error!("{}", msg);
Err(libwallet::ErrorKind::ClientCallback(msg))?
return Err(libwallet::ErrorKind::ClientCallback(msg).into());
}
};
let block_height = match out.block_height {
@@ -302,7 +300,7 @@ impl NodeClient for HTTPNodeClient {
out.commit,
out);
error!("{}", msg);
Err(libwallet::ErrorKind::ClientCallback(msg))?
return Err(libwallet::ErrorKind::ClientCallback(msg).into());
}
};
api_outputs.push((
@@ -322,7 +320,7 @@ impl NodeClient for HTTPNodeClient {
addr, e
);
let report = format!("outputs by pmmr index: {}", e);
Err(libwallet::ErrorKind::ClientCallback(report))?
Err(libwallet::ErrorKind::ClientCallback(report).into())
}
}
}
@@ -349,7 +347,7 @@ impl NodeClient for HTTPNodeClient {
// if we got anything other than 200 back from server, bye
error!("heightstopmmr: error contacting {}. Error: {}", addr, e);
let report = format!(": {}", e);
Err(libwallet::ErrorKind::ClientCallback(report))?
Err(libwallet::ErrorKind::ClientCallback(report).into())
}
}
}
+2 -3
View File
@@ -43,7 +43,7 @@ fn get_output_local(chain: &chain::Chain, commit: &pedersen::Commitment) -> Opti
];
for x in outputs.iter() {
if let Ok(_) = chain.is_unspent(&x) {
if chain.is_unspent(&x).is_ok() {
let block_height = chain.get_header_for_output(&x).unwrap().height;
let output_pos = chain.get_output_pos(&x.commit).unwrap_or(0);
return Some(api::Output::new(&commit, block_height, output_pos));
@@ -221,8 +221,7 @@ where
let slate_i = owner::init_send_tx(&mut **w, keychain_mask, args, test_mode)?;
let slate = client.send_tx_slate_direct(dest, &slate_i)?;
owner::tx_lock_outputs(&mut **w, keychain_mask, &slate, 0)?;
let slate = owner::finalize_tx(&mut **w, keychain_mask, &slate)?;
slate
owner::finalize_tx(&mut **w, keychain_mask, &slate)?
};
let client = {
let mut w_lock = wallet.lock();
+11 -12
View File
@@ -100,7 +100,7 @@ where
let verifier_cache = Arc::new(RwLock::new(LruVerifierCache::new()));
let dir_name = format!("{}/.grin", chain_dir);
let c = Chain::init(
dir_name.to_string(),
dir_name,
Arc::new(NoopAdapter {}),
genesis_block,
pow::verify_size,
@@ -109,15 +109,14 @@ where
)
.unwrap();
let (tx, rx) = channel();
let retval = WalletProxy {
WalletProxy {
chain_dir: chain_dir.to_owned(),
chain: Arc::new(c),
tx: tx,
rx: rx,
wallets: HashMap::new(),
running: Arc::new(AtomicBool::new(false)),
};
retval
}
}
/// Add wallet with a given "address"
@@ -274,12 +273,12 @@ where
&mut self,
m: WalletProxyMessage,
) -> Result<WalletProxyMessage, libwallet::Error> {
let split = m.body.split(",");
let split = m.body.split(',');
//let mut api_outputs: HashMap<pedersen::Commitment, String> = HashMap::new();
let mut outputs: Vec<api::Output> = vec![];
for o in split {
let o_str = String::from(o);
if o_str.len() == 0 {
if o_str.is_empty() {
continue;
}
let c = util::from_hex(o_str).unwrap();
@@ -302,7 +301,7 @@ where
&mut self,
m: WalletProxyMessage,
) -> Result<WalletProxyMessage, libwallet::Error> {
let split = m.body.split(",").collect::<Vec<&str>>();
let split = m.body.split(',').collect::<Vec<&str>>();
let start_index = split[0].parse::<u64>().unwrap();
let max = split[1].parse::<u64>().unwrap();
let end_index = split[2].parse::<u64>().unwrap();
@@ -325,7 +324,7 @@ where
&mut self,
m: WalletProxyMessage,
) -> Result<WalletProxyMessage, libwallet::Error> {
let split = m.body.split(",").collect::<Vec<&str>>();
let split = m.body.split(',').collect::<Vec<&str>>();
let start_index = split[0].parse::<u64>().unwrap();
let end_index = split[1].parse::<u64>().unwrap();
let end_index = match end_index {
@@ -347,7 +346,7 @@ where
&mut self,
m: WalletProxyMessage,
) -> Result<WalletProxyMessage, libwallet::Error> {
let split = m.body.split(",").collect::<Vec<&str>>();
let split = m.body.split(',').collect::<Vec<&str>>();
let excess = split[0].parse::<String>().unwrap();
let min = split[1].parse::<u64>().unwrap();
let max = split[2].parse::<u64>().unwrap();
@@ -457,7 +456,7 @@ impl NodeClient for LocalWalletClient {
}
let r = self.rx.lock();
let m = r.recv().unwrap();
trace!("Received post_tx response: {:?}", m.clone());
trace!("Received post_tx response: {:?}", m);
Ok(())
}
@@ -484,7 +483,7 @@ impl NodeClient for LocalWalletClient {
.context(libwallet::ErrorKind::ClientCallback(
"Parsing get_height response".to_owned(),
))?;
let split: Vec<&str> = res.split(",").collect();
let split: Vec<&str> = res.split(',').collect();
Ok((split[0].parse::<u64>().unwrap(), split[1].to_owned()))
}
@@ -495,7 +494,7 @@ impl NodeClient for LocalWalletClient {
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
let query_params: Vec<String> = wallet_outputs
.iter()
.map(|commit| format!("{}", util::to_hex(commit.as_ref().to_vec())))
.map(|commit| util::to_hex(commit.as_ref().to_vec()))
.collect();
let query_str = query_params.join(",");
let m = WalletProxyMessage {
+17 -17
View File
@@ -28,13 +28,13 @@ use std::path::{Path, MAIN_SEPARATOR};
use failure::ResultExt;
const SEC_KEY_FILE: &'static str = "hs_ed25519_secret_key";
const PUB_KEY_FILE: &'static str = "hs_ed25519_public_key";
const HOSTNAME_FILE: &'static str = "hostname";
const TORRC_FILE: &'static str = "torrc";
const TOR_DATA_DIR: &'static str = "data";
const AUTH_CLIENTS_DIR: &'static str = "authorized_clients";
const HIDDEN_SERVICES_DIR: &'static str = "onion_service_addresses";
const SEC_KEY_FILE: &str = "hs_ed25519_secret_key";
const PUB_KEY_FILE: &str = "hs_ed25519_public_key";
const HOSTNAME_FILE: &str = "hostname";
const TORRC_FILE: &str = "torrc";
const TOR_DATA_DIR: &str = "data";
const AUTH_CLIENTS_DIR: &str = "authorized_clients";
const HIDDEN_SERVICES_DIR: &str = "onion_service_addresses";
#[cfg(unix)]
fn set_permissions(file_path: &str) -> Result<(), Error> {
@@ -100,7 +100,7 @@ pub fn create_onion_service_sec_key_file(
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, SEC_KEY_FILE);
let mut file = File::create(key_file_path).context(ErrorKind::IO)?;
// Tag is always 32 bytes, so pad with null zeroes
file.write("== ed25519v1-secret: type0 ==\0\0\0".as_bytes())
file.write(b"== ed25519v1-secret: type0 ==\0\0\0")
.context(ErrorKind::IO)?;
let expanded_skey: ExpandedSecretKey = ExpandedSecretKey::from(sec_key);
file.write_all(&expanded_skey.to_bytes())
@@ -115,7 +115,7 @@ pub fn create_onion_service_pub_key_file(
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, PUB_KEY_FILE);
let mut file = File::create(key_file_path).context(ErrorKind::IO)?;
// Tag is always 32 bytes, so pad with null zeroes
file.write("== ed25519v1-public: type0 ==\0\0\0".as_bytes())
file.write(b"== ed25519v1-public: type0 ==\0\0\0")
.context(ErrorKind::IO)?;
file.write_all(pub_key.as_bytes()).context(ErrorKind::IO)?;
Ok(())
@@ -170,7 +170,7 @@ pub fn output_torrc(
tor_config_directory: &str,
wallet_listener_addr: &str,
socks_port: &str,
service_dirs: &Vec<String>,
service_dirs: &[String],
) -> Result<(), Error> {
let torrc_file_path = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TORRC_FILE);
@@ -195,7 +195,7 @@ pub fn output_torrc(
pub fn output_tor_listener_config(
tor_config_directory: &str,
wallet_listener_addr: &str,
listener_keys: &Vec<SecretKey>,
listener_keys: &[SecretKey],
) -> Result<(), Error> {
let tor_data_dir = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TOR_DATA_DIR);
@@ -228,7 +228,7 @@ pub fn output_tor_sender_config(
// create data directory if it doesn't exist
fs::create_dir_all(&tor_config_dir).context(ErrorKind::IO)?;
output_torrc(tor_config_dir, "", socks_listener_addr, &vec![])?;
output_torrc(tor_config_dir, "", socks_listener_addr, &[])?;
Ok(())
}
@@ -238,13 +238,13 @@ pub fn is_tor_address(input: &str) -> Result<(), Error> {
Ok(_) => Ok(()),
Err(e) => {
let msg = format!("{:?}", e);
Err(ErrorKind::NotOnion(msg).to_owned())?
Err(ErrorKind::NotOnion(msg).into())
}
}
}
pub fn complete_tor_address(input: &str) -> Result<String, Error> {
let _ = is_tor_address(input)?;
is_tor_address(input)?;
let mut input = input.to_uppercase();
if !input.starts_with("HTTP://") && !input.starts_with("HTTPS://") {
input = format!("HTTP://{}", input);
@@ -278,7 +278,7 @@ mod tests {
setup(test_dir);
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let mut test_rng = StepRng::new(1234567890u64, 1);
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
output_onion_service_config(test_dir, &sec_key)?;
clean_output_dir(test_dir);
@@ -291,9 +291,9 @@ mod tests {
setup(test_dir);
let secp_inst = static_secp_instance();
let secp = secp_inst.lock();
let mut test_rng = StepRng::new(1234567890u64, 1);
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
output_tor_listener_config(test_dir, "127.0.0.1:3415", &vec![sec_key])?;
output_tor_listener_config(test_dir, "127.0.0.1:3415", &[sec_key])?;
clean_output_dir(test_dir);
Ok(())
}
+7 -7
View File
@@ -61,9 +61,9 @@ use std::thread;
use sysinfo::{Process, ProcessExt, Signal};
#[cfg(windows)]
const TOR_EXE_NAME: &'static str = "tor.exe";
const TOR_EXE_NAME: &str = "tor.exe";
#[cfg(not(windows))]
const TOR_EXE_NAME: &'static str = "tor";
const TOR_EXE_NAME: &str = "tor";
#[derive(Debug)]
pub enum Error {
@@ -160,7 +160,7 @@ impl TorProcess {
let pid_file_name = format!("{}{}pid", d, MAIN_SEPARATOR);
// kill off PID if its already running
if Path::new(&pid_file_name).exists() {
let pid = fs::read_to_string(&pid_file_name).map_err(|err| Error::IO(err))?;
let pid = fs::read_to_string(&pid_file_name).map_err(Error::IO)?;
let pid = pid
.parse::<i32>()
.map_err(|err| Error::PID(format!("{:?}", err)))?;
@@ -186,9 +186,9 @@ impl TorProcess {
// split out the process id, so if we don't exit cleanly
// we can take it down on the next run
let pid_file_name = format!("{}{}pid", d, MAIN_SEPARATOR);
let mut file = File::create(pid_file_name).map_err(|err| Error::IO(err))?;
let mut file = File::create(pid_file_name).map_err(Error::IO)?;
file.write_all(format!("{}", tor_process.id()).as_bytes())
.map_err(|err| Error::IO(err))?;
.map_err(Error::IO)?;
}
let stdout = BufReader::new(tor_process.stdout.take().unwrap());
@@ -228,7 +228,7 @@ impl TorProcess {
completion_perc: u8,
) -> Result<BufReader<ChildStdout>, Error> {
let re_bootstrap = Regex::new(r"^\[notice\] Bootstrapped (?P<perc>[0-9]+)%(.*): ")
.map_err(|err| Error::Regex(err))?;
.map_err(Error::Regex)?;
let timestamp_len = "May 16 02:50:08.792".len();
let mut warnings = Vec::new();
@@ -253,7 +253,7 @@ impl TorProcess {
.captures(line)
.and_then(|c| c.name("perc"))
.and_then(|pc| pc.as_str().parse::<u8>().ok())
.ok_or(Error::InvalidBootstrapLine(line.to_string()))?;
.ok_or_else(|| Error::InvalidBootstrapLine(line.to_string()))?;
if perc >= completion_perc {
break;