mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-10-17 07:11:36 +02:00
Fixed issue with top-dir without init, better absolut e path and more cleanup
This commit is contained in:
+80
-80
@@ -1,81 +1,81 @@
|
||||
[package]
|
||||
name = "grin_wallet_impls"
|
||||
version = "5.4.0-alpha.1"
|
||||
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
|
||||
description = "Concrete types derived from libwallet traits"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/mimblewimble/grin-wallet"
|
||||
keywords = [ "crypto", "grin", "mimblewimble" ]
|
||||
exclude = ["**/*.grin", "**/*.grin2"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
blake2-rfc = "0.2"
|
||||
thiserror = "1"
|
||||
futures = "0.3"
|
||||
rand = "0.6"
|
||||
serde = "1"
|
||||
serde_derive = "1"
|
||||
serde_json = "1"
|
||||
log = "0.4"
|
||||
ring = "0.16"
|
||||
uuid = { version = "0.8", features = ["serde", "v4"] }
|
||||
chrono = { version = "0.4.11", features = ["serde"] }
|
||||
lazy_static = "1"
|
||||
tokio = { version = "0.2", features = ["full"] }
|
||||
reqwest = { version = "0.10", features = ["rustls-tls", "socks"] }
|
||||
|
||||
#Socks/Tor/Bridge/Proxy
|
||||
byteorder = "1"
|
||||
ed25519-dalek = "1.0.0-pre.4"
|
||||
x25519-dalek = "0.6"
|
||||
data-encoding = "2"
|
||||
regex = "1.3"
|
||||
timer = "0.2"
|
||||
sysinfo = "0.29"
|
||||
base64 = "0.12.0"
|
||||
url = "2.1"
|
||||
|
||||
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
|
||||
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
|
||||
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" }
|
||||
|
||||
##### Grin Imports
|
||||
|
||||
# For Release
|
||||
grin_core = "5.3.3"
|
||||
grin_keychain = "5.3.3"
|
||||
grin_chain = "5.3.3"
|
||||
grin_util = "5.3.3"
|
||||
grin_api = "5.3.3"
|
||||
grin_store = "5.3.3"
|
||||
|
||||
# For beta release
|
||||
|
||||
# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"}
|
||||
# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_chain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
|
||||
# For bleeding edge
|
||||
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
|
||||
# For local testing
|
||||
# grin_core = { path = "../../grin/core"}
|
||||
# grin_keychain = { path = "../../grin/keychain"}
|
||||
# grin_chain = { path = "../../grin/chain"}
|
||||
# grin_util = { path = "../../grin/util"}
|
||||
# grin_api = { path = "../../grin/api"}
|
||||
# grin_store = { path = "../../grin/store"}
|
||||
|
||||
#####
|
||||
|
||||
[dev-dependencies]
|
||||
[package]
|
||||
name = "grin_wallet_impls"
|
||||
version = "5.4.0-alpha.1"
|
||||
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
|
||||
description = "Concrete types derived from libwallet traits"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/mimblewimble/grin-wallet"
|
||||
keywords = [ "crypto", "grin", "mimblewimble" ]
|
||||
exclude = ["**/*.grin", "**/*.grin2"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
blake2-rfc = "0.2"
|
||||
thiserror = "1"
|
||||
futures = "0.3"
|
||||
rand = "0.6"
|
||||
serde = "1"
|
||||
serde_derive = "1"
|
||||
serde_json = "1"
|
||||
log = "0.4"
|
||||
ring = "0.16"
|
||||
uuid = { version = "0.8", features = ["serde", "v4"] }
|
||||
chrono = { version = "0.4.11", features = ["serde"] }
|
||||
lazy_static = "1"
|
||||
tokio = { version = "0.2", features = ["full"] }
|
||||
reqwest = { version = "0.10", features = ["rustls-tls", "socks"] }
|
||||
|
||||
#Socks/Tor/Bridge/Proxy
|
||||
byteorder = "1"
|
||||
ed25519-dalek = "1.0.0-pre.4"
|
||||
x25519-dalek = "0.6"
|
||||
data-encoding = "2"
|
||||
regex = "1.3"
|
||||
timer = "0.2"
|
||||
sysinfo = "0.29"
|
||||
base64 = "0.12.0"
|
||||
url = "2.1"
|
||||
|
||||
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
|
||||
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
|
||||
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" }
|
||||
|
||||
##### Grin Imports
|
||||
|
||||
# For Release
|
||||
grin_core = "5.3.3"
|
||||
grin_keychain = "5.3.3"
|
||||
grin_chain = "5.3.3"
|
||||
grin_util = "5.3.3"
|
||||
grin_api = "5.3.3"
|
||||
grin_store = "5.3.3"
|
||||
|
||||
# For beta release
|
||||
|
||||
# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"}
|
||||
# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_chain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
|
||||
|
||||
# For bleeding edge
|
||||
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
# grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
|
||||
|
||||
# For local testing
|
||||
# grin_core = { path = "../../grin/core"}
|
||||
# grin_keychain = { path = "../../grin/keychain"}
|
||||
# grin_chain = { path = "../../grin/chain"}
|
||||
# grin_util = { path = "../../grin/util"}
|
||||
# grin_api = { path = "../../grin/api"}
|
||||
# grin_store = { path = "../../grin/store"}
|
||||
|
||||
#####
|
||||
|
||||
[dev-dependencies]
|
||||
"remove_dir_all" = "0.7"
|
||||
+73
-73
@@ -1,73 +1,73 @@
|
||||
// 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.
|
||||
|
||||
/// File Output 'plugin' implementation
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use crate::libwallet::{Error, Slate, SlateVersion, VersionedBinSlate, VersionedSlate};
|
||||
use crate::{SlateGetter, SlatePutter};
|
||||
use grin_wallet_util::byte_ser;
|
||||
use std::convert::TryFrom;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PathToSlate(pub PathBuf);
|
||||
|
||||
impl SlatePutter for PathToSlate {
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> {
|
||||
// For testing (output raw slate data for reference)
|
||||
/*{
|
||||
let mut raw_path = self.0.clone();
|
||||
raw_path.set_extension("raw");
|
||||
let mut raw_slate = File::create(&raw_path)?;
|
||||
raw_slate.write_all(&format!("{:?}", slate).as_bytes())?;
|
||||
raw_slate.sync_all()?;
|
||||
}*/
|
||||
let mut pub_tx = File::create(&self.0)?;
|
||||
// TODO:
|
||||
let out_slate = VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?;
|
||||
if as_bin {
|
||||
let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlateSer)?;
|
||||
pub_tx.write_all(&byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlateSer)?)?;
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
serde_json::to_string_pretty(&out_slate)
|
||||
.map_err(|_| Error::SlateSer)?
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
pub_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SlateGetter for PathToSlate {
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error> {
|
||||
// try as bin first, then as json
|
||||
let mut pub_tx_f = File::open(&self.0)?;
|
||||
let mut data = Vec::new();
|
||||
pub_tx_f.read_to_end(&mut data)?;
|
||||
let bin_res = byte_ser::from_bytes::<VersionedBinSlate>(&data);
|
||||
if let Err(e) = bin_res {
|
||||
debug!("Not a valid binary slate: {} - Will try JSON", e);
|
||||
} else if let Ok(s) = bin_res {
|
||||
return Ok((Slate::upgrade(s.into())?, true));
|
||||
}
|
||||
|
||||
// Otherwise try json
|
||||
let content = String::from_utf8(data).map_err(|_| Error::SlateSer)?;
|
||||
Ok((Slate::deserialize_upgrade(&content)?, false))
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
/// File Output 'plugin' implementation
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use crate::libwallet::{Error, Slate, SlateVersion, VersionedBinSlate, VersionedSlate};
|
||||
use crate::{SlateGetter, SlatePutter};
|
||||
use grin_wallet_util::byte_ser;
|
||||
use std::convert::TryFrom;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PathToSlate(pub PathBuf);
|
||||
|
||||
impl SlatePutter for PathToSlate {
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> {
|
||||
// For testing (output raw slate data for reference)
|
||||
/*{
|
||||
let mut raw_path = self.0.clone();
|
||||
raw_path.set_extension("raw");
|
||||
let mut raw_slate = File::create(&raw_path)?;
|
||||
raw_slate.write_all(&format!("{:?}", slate).as_bytes())?;
|
||||
raw_slate.sync_all()?;
|
||||
}*/
|
||||
let mut pub_tx = File::create(&self.0)?;
|
||||
// TODO:
|
||||
let out_slate = VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?;
|
||||
if as_bin {
|
||||
let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlateSer)?;
|
||||
pub_tx.write_all(&byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlateSer)?)?;
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
serde_json::to_string_pretty(&out_slate)
|
||||
.map_err(|_| Error::SlateSer)?
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
pub_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SlateGetter for PathToSlate {
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error> {
|
||||
// try as bin first, then as json
|
||||
let mut pub_tx_f = File::open(&self.0)?;
|
||||
let mut data = Vec::new();
|
||||
pub_tx_f.read_to_end(&mut data)?;
|
||||
let bin_res = byte_ser::from_bytes::<VersionedBinSlate>(&data);
|
||||
if let Err(e) = bin_res {
|
||||
debug!("Not a valid binary slate: {} - Will try JSON", e);
|
||||
} else if let Ok(s) = bin_res {
|
||||
return Ok((Slate::upgrade(s.into())?, true));
|
||||
}
|
||||
|
||||
// Otherwise try json
|
||||
let content = String::from_utf8(data).map_err(|_| Error::SlateSer)?;
|
||||
Ok((Slate::deserialize_upgrade(&content)?, false))
|
||||
}
|
||||
}
|
||||
|
||||
+292
-292
@@ -1,292 +1,292 @@
|
||||
// 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.
|
||||
|
||||
/// HTTP Wallet 'plugin' implementation
|
||||
use crate::client_utils::{Client, ClientError};
|
||||
use crate::libwallet::slate_versions::{SlateVersion, VersionedSlate};
|
||||
use crate::libwallet::{Error, Slate};
|
||||
use crate::tor::bridge::TorBridge;
|
||||
use crate::tor::proxy::TorProxy;
|
||||
use crate::SlateSender;
|
||||
use grin_wallet_config::types::{TorBridgeConfig, TorProxyConfig};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::tor::config as tor_config;
|
||||
use crate::tor::process as tor_process;
|
||||
|
||||
const TOR_CONFIG_PATH: &str = "tor/sender";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HttpSlateSender {
|
||||
base_url: String,
|
||||
use_socks: bool,
|
||||
socks_proxy_addr: Option<SocketAddr>,
|
||||
tor_config_dir: String,
|
||||
process: Option<Arc<tor_process::TorProcess>>,
|
||||
bridge: TorBridgeConfig,
|
||||
proxy: TorProxyConfig,
|
||||
}
|
||||
|
||||
impl HttpSlateSender {
|
||||
/// Create, return Err if scheme is not "http"
|
||||
fn new(base_url: &str) -> Result<HttpSlateSender, SchemeNotHttp> {
|
||||
if !base_url.starts_with("http") && !base_url.starts_with("https") {
|
||||
Err(SchemeNotHttp)
|
||||
} else {
|
||||
Ok(HttpSlateSender {
|
||||
base_url: base_url.to_owned(),
|
||||
use_socks: false,
|
||||
socks_proxy_addr: None,
|
||||
tor_config_dir: String::from(""),
|
||||
process: None,
|
||||
bridge: TorBridgeConfig::default(),
|
||||
proxy: TorProxyConfig::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch to using socks proxy
|
||||
pub fn with_socks_proxy(
|
||||
base_url: &str,
|
||||
proxy_addr: &str,
|
||||
tor_config_dir: &str,
|
||||
tor_bridge: TorBridgeConfig,
|
||||
tor_proxy: TorProxyConfig,
|
||||
) -> Result<HttpSlateSender, SchemeNotHttp> {
|
||||
let mut ret = Self::new(base_url)?;
|
||||
ret.use_socks = true;
|
||||
//TODO: Unwrap
|
||||
ret.socks_proxy_addr = Some(SocketAddr::V4(proxy_addr.parse().unwrap()));
|
||||
ret.tor_config_dir = tor_config_dir.into();
|
||||
ret.bridge = tor_bridge;
|
||||
ret.proxy = tor_proxy;
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
/// launch TOR process
|
||||
pub fn launch_tor(&mut self) -> Result<(), Error> {
|
||||
// set up tor send process if needed
|
||||
let mut tor = tor_process::TorProcess::new();
|
||||
if self.use_socks && self.process.is_none() {
|
||||
let tor_dir = format!(
|
||||
"{}{}{}",
|
||||
&self.tor_config_dir, MAIN_SEPARATOR, TOR_CONFIG_PATH
|
||||
);
|
||||
info!(
|
||||
"Starting TOR Process for send at {:?}",
|
||||
self.socks_proxy_addr
|
||||
);
|
||||
|
||||
let mut hm_tor_bridge: HashMap<String, String> = HashMap::new();
|
||||
if self.bridge.bridge_line.is_some() {
|
||||
let bridge_struct = TorBridge::try_from(self.bridge.clone())
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
hm_tor_bridge = bridge_struct
|
||||
.to_hashmap()
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
}
|
||||
|
||||
let mut hm_tor_proxy: HashMap<String, String> = HashMap::new();
|
||||
if self.proxy.transport.is_some() || self.proxy.allowed_port.is_some() {
|
||||
let proxy = TorProxy::try_from(self.proxy.clone())
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
hm_tor_proxy = proxy
|
||||
.to_hashmap()
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
}
|
||||
|
||||
tor_config::output_tor_sender_config(
|
||||
&tor_dir,
|
||||
&self.socks_proxy_addr.unwrap().to_string(),
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)
|
||||
.map_err(|e| Error::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| Error::TorProcess(format!("{:?}", e)))?;
|
||||
self.process = Some(Arc::new(tor));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check version of the listening wallet
|
||||
pub fn check_other_version(&mut self, url: &str) -> Result<SlateVersion, Error> {
|
||||
self.launch_tor()?;
|
||||
let req = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "check_version",
|
||||
"id": 1,
|
||||
"params": []
|
||||
});
|
||||
|
||||
let res: String = self.post(url, None, req).map_err(|e| {
|
||||
let mut report = format!("Performing version check (is recipient listening?): {}", e);
|
||||
let err_string = format!("{}", e);
|
||||
if err_string.contains("404") {
|
||||
// Report that the other version of the wallet is out of date
|
||||
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);
|
||||
}
|
||||
Error::ClientCallback(report)
|
||||
})?;
|
||||
|
||||
let res: Value = serde_json::from_str(&res).unwrap();
|
||||
trace!("Response: {}", res);
|
||||
if res["error"] != json!(null) {
|
||||
let report = format!(
|
||||
"Posting transaction slate: Error: {}, Message: {}",
|
||||
res["error"]["code"], res["error"]["message"]
|
||||
);
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
let resp_value = res["result"]["Ok"].clone();
|
||||
trace!("resp_value: {}", resp_value.clone());
|
||||
let foreign_api_version: u16 =
|
||||
serde_json::from_value(resp_value["foreign_api_version"].clone()).unwrap();
|
||||
let supported_slate_versions: Vec<String> =
|
||||
serde_json::from_value(resp_value["supported_slate_versions"].clone()).unwrap();
|
||||
|
||||
// trivial tests for now, but will be expanded later
|
||||
if foreign_api_version < 2 {
|
||||
let report = "Other wallet reports unrecognized API format.".to_string();
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
if supported_slate_versions.contains(&"V4".to_owned()) {
|
||||
return Ok(SlateVersion::V4);
|
||||
}
|
||||
|
||||
let report = "Unable to negotiate slate format with other wallet.".to_string();
|
||||
error!("{}", report);
|
||||
Err(Error::ClientCallback(report))
|
||||
}
|
||||
|
||||
fn post<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: IN,
|
||||
) -> Result<String, ClientError>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let client = if !self.use_socks {
|
||||
Client::new()
|
||||
} else {
|
||||
Client::with_socks_proxy(
|
||||
self.socks_proxy_addr
|
||||
.ok_or_else(|| ClientError::Internal("No socks proxy address set".into()))?,
|
||||
)
|
||||
}
|
||||
.map_err(|_| ClientError::Internal("Unable to create http client".into()))?;
|
||||
let req = client.create_post_request(url, api_secret, &input)?;
|
||||
let res = client.send_request(req)?;
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl SlateSender for HttpSlateSender {
|
||||
fn send_tx(&mut self, slate: &Slate, finalize: bool) -> Result<Slate, Error> {
|
||||
let trailing = match self.base_url.ends_with('/') {
|
||||
true => "",
|
||||
false => "/",
|
||||
};
|
||||
let url_str = format!("{}{}v2/foreign", self.base_url, trailing);
|
||||
|
||||
self.launch_tor()?;
|
||||
|
||||
let slate_send = match self.check_other_version(&url_str)? {
|
||||
SlateVersion::V4 => VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?,
|
||||
};
|
||||
// Note: not using easy-jsonrpc as don't want the dependencies in this crate
|
||||
let req = match finalize {
|
||||
false => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "receive_tx",
|
||||
"id": 1,
|
||||
"params": [
|
||||
slate_send,
|
||||
null,
|
||||
null
|
||||
]
|
||||
}),
|
||||
true => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "finalize_tx",
|
||||
"id": 1,
|
||||
"params": [
|
||||
slate_send
|
||||
]
|
||||
}),
|
||||
};
|
||||
|
||||
trace!("Sending receive_tx request: {}", req);
|
||||
|
||||
let res: String = self.post(&url_str, None, req).map_err(|e| {
|
||||
let report = format!(
|
||||
"Sending transaction slate to other wallet (is recipient listening?): {}",
|
||||
e
|
||||
);
|
||||
Error::ClientCallback(report)
|
||||
})?;
|
||||
|
||||
let res: Value = serde_json::from_str(&res).unwrap();
|
||||
trace!("Response: {}", res);
|
||||
if res["error"] != json!(null) {
|
||||
let report = format!(
|
||||
"Posting transaction slate: Error: {}, Message: {}",
|
||||
res["error"]["code"], res["error"]["message"]
|
||||
);
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
let slate_value = res["result"]["Ok"].clone();
|
||||
|
||||
trace!("slate_value: {}", slate_value);
|
||||
let slate = Slate::deserialize_upgrade(&serde_json::to_string(&slate_value).unwrap())
|
||||
.map_err(|e| {
|
||||
error!("Error deserializing response slate: {}", e);
|
||||
Error::SlateDeser
|
||||
})?;
|
||||
|
||||
Ok(slate)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
|
||||
pub struct SchemeNotHttp;
|
||||
|
||||
impl Into<Error> for SchemeNotHttp {
|
||||
fn into(self) -> Error {
|
||||
let err_str = "url scheme must be http".to_string();
|
||||
Error::GenericError(err_str)
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
/// HTTP Wallet 'plugin' implementation
|
||||
use crate::client_utils::{Client, ClientError};
|
||||
use crate::libwallet::slate_versions::{SlateVersion, VersionedSlate};
|
||||
use crate::libwallet::{Error, Slate};
|
||||
use crate::tor::bridge::TorBridge;
|
||||
use crate::tor::proxy::TorProxy;
|
||||
use crate::SlateSender;
|
||||
use grin_wallet_config::types::{TorBridgeConfig, TorProxyConfig};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::tor::config as tor_config;
|
||||
use crate::tor::process as tor_process;
|
||||
|
||||
const TOR_CONFIG_PATH: &str = "tor/sender";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HttpSlateSender {
|
||||
base_url: String,
|
||||
use_socks: bool,
|
||||
socks_proxy_addr: Option<SocketAddr>,
|
||||
tor_config_dir: String,
|
||||
process: Option<Arc<tor_process::TorProcess>>,
|
||||
bridge: TorBridgeConfig,
|
||||
proxy: TorProxyConfig,
|
||||
}
|
||||
|
||||
impl HttpSlateSender {
|
||||
/// Create, return Err if scheme is not "http"
|
||||
fn new(base_url: &str) -> Result<HttpSlateSender, SchemeNotHttp> {
|
||||
if !base_url.starts_with("http") && !base_url.starts_with("https") {
|
||||
Err(SchemeNotHttp)
|
||||
} else {
|
||||
Ok(HttpSlateSender {
|
||||
base_url: base_url.to_owned(),
|
||||
use_socks: false,
|
||||
socks_proxy_addr: None,
|
||||
tor_config_dir: String::from(""),
|
||||
process: None,
|
||||
bridge: TorBridgeConfig::default(),
|
||||
proxy: TorProxyConfig::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch to using socks proxy
|
||||
pub fn with_socks_proxy(
|
||||
base_url: &str,
|
||||
proxy_addr: &str,
|
||||
tor_config_dir: &str,
|
||||
tor_bridge: TorBridgeConfig,
|
||||
tor_proxy: TorProxyConfig,
|
||||
) -> Result<HttpSlateSender, SchemeNotHttp> {
|
||||
let mut ret = Self::new(base_url)?;
|
||||
ret.use_socks = true;
|
||||
//TODO: Unwrap
|
||||
ret.socks_proxy_addr = Some(SocketAddr::V4(proxy_addr.parse().unwrap()));
|
||||
ret.tor_config_dir = tor_config_dir.into();
|
||||
ret.bridge = tor_bridge;
|
||||
ret.proxy = tor_proxy;
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
/// launch TOR process
|
||||
pub fn launch_tor(&mut self) -> Result<(), Error> {
|
||||
// set up tor send process if needed
|
||||
let mut tor = tor_process::TorProcess::new();
|
||||
if self.use_socks && self.process.is_none() {
|
||||
let tor_dir = format!(
|
||||
"{}{}{}",
|
||||
&self.tor_config_dir, MAIN_SEPARATOR, TOR_CONFIG_PATH
|
||||
);
|
||||
info!(
|
||||
"Starting TOR Process for send at {:?}",
|
||||
self.socks_proxy_addr
|
||||
);
|
||||
|
||||
let mut hm_tor_bridge: HashMap<String, String> = HashMap::new();
|
||||
if self.bridge.bridge_line.is_some() {
|
||||
let bridge_struct = TorBridge::try_from(self.bridge.clone())
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
hm_tor_bridge = bridge_struct
|
||||
.to_hashmap()
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
}
|
||||
|
||||
let mut hm_tor_proxy: HashMap<String, String> = HashMap::new();
|
||||
if self.proxy.transport.is_some() || self.proxy.allowed_port.is_some() {
|
||||
let proxy = TorProxy::try_from(self.proxy.clone())
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
hm_tor_proxy = proxy
|
||||
.to_hashmap()
|
||||
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
|
||||
}
|
||||
|
||||
tor_config::output_tor_sender_config(
|
||||
&tor_dir,
|
||||
&self.socks_proxy_addr.unwrap().to_string(),
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)
|
||||
.map_err(|e| Error::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| Error::TorProcess(format!("{:?}", e)))?;
|
||||
self.process = Some(Arc::new(tor));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check version of the listening wallet
|
||||
pub fn check_other_version(&mut self, url: &str) -> Result<SlateVersion, Error> {
|
||||
self.launch_tor()?;
|
||||
let req = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "check_version",
|
||||
"id": 1,
|
||||
"params": []
|
||||
});
|
||||
|
||||
let res: String = self.post(url, None, req).map_err(|e| {
|
||||
let mut report = format!("Performing version check (is recipient listening?): {}", e);
|
||||
let err_string = format!("{}", e);
|
||||
if err_string.contains("404") {
|
||||
// Report that the other version of the wallet is out of date
|
||||
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);
|
||||
}
|
||||
Error::ClientCallback(report)
|
||||
})?;
|
||||
|
||||
let res: Value = serde_json::from_str(&res).unwrap();
|
||||
trace!("Response: {}", res);
|
||||
if res["error"] != json!(null) {
|
||||
let report = format!(
|
||||
"Posting transaction slate: Error: {}, Message: {}",
|
||||
res["error"]["code"], res["error"]["message"]
|
||||
);
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
let resp_value = res["result"]["Ok"].clone();
|
||||
trace!("resp_value: {}", resp_value.clone());
|
||||
let foreign_api_version: u16 =
|
||||
serde_json::from_value(resp_value["foreign_api_version"].clone()).unwrap();
|
||||
let supported_slate_versions: Vec<String> =
|
||||
serde_json::from_value(resp_value["supported_slate_versions"].clone()).unwrap();
|
||||
|
||||
// trivial tests for now, but will be expanded later
|
||||
if foreign_api_version < 2 {
|
||||
let report = "Other wallet reports unrecognized API format.".to_string();
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
if supported_slate_versions.contains(&"V4".to_owned()) {
|
||||
return Ok(SlateVersion::V4);
|
||||
}
|
||||
|
||||
let report = "Unable to negotiate slate format with other wallet.".to_string();
|
||||
error!("{}", report);
|
||||
Err(Error::ClientCallback(report))
|
||||
}
|
||||
|
||||
fn post<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: IN,
|
||||
) -> Result<String, ClientError>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let client = if !self.use_socks {
|
||||
Client::new()
|
||||
} else {
|
||||
Client::with_socks_proxy(
|
||||
self.socks_proxy_addr
|
||||
.ok_or_else(|| ClientError::Internal("No socks proxy address set".into()))?,
|
||||
)
|
||||
}
|
||||
.map_err(|_| ClientError::Internal("Unable to create http client".into()))?;
|
||||
let req = client.create_post_request(url, api_secret, &input)?;
|
||||
let res = client.send_request(req)?;
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl SlateSender for HttpSlateSender {
|
||||
fn send_tx(&mut self, slate: &Slate, finalize: bool) -> Result<Slate, Error> {
|
||||
let trailing = match self.base_url.ends_with('/') {
|
||||
true => "",
|
||||
false => "/",
|
||||
};
|
||||
let url_str = format!("{}{}v2/foreign", self.base_url, trailing);
|
||||
|
||||
self.launch_tor()?;
|
||||
|
||||
let slate_send = match self.check_other_version(&url_str)? {
|
||||
SlateVersion::V4 => VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?,
|
||||
};
|
||||
// Note: not using easy-jsonrpc as don't want the dependencies in this crate
|
||||
let req = match finalize {
|
||||
false => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "receive_tx",
|
||||
"id": 1,
|
||||
"params": [
|
||||
slate_send,
|
||||
null,
|
||||
null
|
||||
]
|
||||
}),
|
||||
true => json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "finalize_tx",
|
||||
"id": 1,
|
||||
"params": [
|
||||
slate_send
|
||||
]
|
||||
}),
|
||||
};
|
||||
|
||||
trace!("Sending receive_tx request: {}", req);
|
||||
|
||||
let res: String = self.post(&url_str, None, req).map_err(|e| {
|
||||
let report = format!(
|
||||
"Sending transaction slate to other wallet (is recipient listening?): {}",
|
||||
e
|
||||
);
|
||||
Error::ClientCallback(report)
|
||||
})?;
|
||||
|
||||
let res: Value = serde_json::from_str(&res).unwrap();
|
||||
trace!("Response: {}", res);
|
||||
if res["error"] != json!(null) {
|
||||
let report = format!(
|
||||
"Posting transaction slate: Error: {}, Message: {}",
|
||||
res["error"]["code"], res["error"]["message"]
|
||||
);
|
||||
error!("{}", report);
|
||||
return Err(Error::ClientCallback(report));
|
||||
}
|
||||
|
||||
let slate_value = res["result"]["Ok"].clone();
|
||||
|
||||
trace!("slate_value: {}", slate_value);
|
||||
let slate = Slate::deserialize_upgrade(&serde_json::to_string(&slate_value).unwrap())
|
||||
.map_err(|e| {
|
||||
error!("Error deserializing response slate: {}", e);
|
||||
Error::SlateDeser
|
||||
})?;
|
||||
|
||||
Ok(slate)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
|
||||
pub struct SchemeNotHttp;
|
||||
|
||||
impl Into<Error> for SchemeNotHttp {
|
||||
fn into(self) -> Error {
|
||||
let err_str = "url scheme must be http".to_string();
|
||||
Error::GenericError(err_str)
|
||||
}
|
||||
}
|
||||
|
||||
+58
-58
@@ -1,58 +1,58 @@
|
||||
// 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 file;
|
||||
pub mod http;
|
||||
mod slatepack;
|
||||
|
||||
pub use self::file::PathToSlate;
|
||||
pub use self::http::HttpSlateSender;
|
||||
pub use self::slatepack::PathToSlatepack;
|
||||
|
||||
use crate::config::WalletConfig;
|
||||
use crate::libwallet::{Error, Slate};
|
||||
use crate::util::ZeroingString;
|
||||
|
||||
/// Sends transactions to a corresponding SlateReceiver
|
||||
pub trait SlateSender {
|
||||
/// Send a transaction slate to another listening wallet and return result
|
||||
/// TODO: Probably need a slate wrapper type
|
||||
fn send_tx(&mut self, slate: &Slate, finalize: bool) -> Result<Slate, Error>;
|
||||
}
|
||||
|
||||
pub trait SlateReceiver {
|
||||
/// Start a listener, passing received messages to the wallet api directly
|
||||
/// Takes a wallet config for now to avoid needing all sorts of awkward
|
||||
/// type parameters on this trait
|
||||
fn listen(
|
||||
&self,
|
||||
config: WalletConfig,
|
||||
passphrase: ZeroingString,
|
||||
account: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Posts slates to be read later by a corresponding getter
|
||||
pub trait SlatePutter {
|
||||
/// Send a transaction asynchronously
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Checks for a transaction from a corresponding SlatePutter, returns the transaction if it exists
|
||||
pub trait SlateGetter {
|
||||
/// Receive a transaction async. (Actually just read it from wherever and return the slate).
|
||||
/// Returns (Slate, whether it was in binary form)
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error>;
|
||||
}
|
||||
// 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 file;
|
||||
pub mod http;
|
||||
mod slatepack;
|
||||
|
||||
pub use self::file::PathToSlate;
|
||||
pub use self::http::HttpSlateSender;
|
||||
pub use self::slatepack::PathToSlatepack;
|
||||
|
||||
use crate::config::WalletConfig;
|
||||
use crate::libwallet::{Error, Slate};
|
||||
use crate::util::ZeroingString;
|
||||
|
||||
/// Sends transactions to a corresponding SlateReceiver
|
||||
pub trait SlateSender {
|
||||
/// Send a transaction slate to another listening wallet and return result
|
||||
/// TODO: Probably need a slate wrapper type
|
||||
fn send_tx(&mut self, slate: &Slate, finalize: bool) -> Result<Slate, Error>;
|
||||
}
|
||||
|
||||
pub trait SlateReceiver {
|
||||
/// Start a listener, passing received messages to the wallet api directly
|
||||
/// Takes a wallet config for now to avoid needing all sorts of awkward
|
||||
/// type parameters on this trait
|
||||
fn listen(
|
||||
&self,
|
||||
config: WalletConfig,
|
||||
passphrase: ZeroingString,
|
||||
account: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Posts slates to be read later by a corresponding getter
|
||||
pub trait SlatePutter {
|
||||
/// Send a transaction asynchronously
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Checks for a transaction from a corresponding SlatePutter, returns the transaction if it exists
|
||||
pub trait SlateGetter {
|
||||
/// Receive a transaction async. (Actually just read it from wherever and return the slate).
|
||||
/// Returns (Slate, whether it was in binary form)
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error>;
|
||||
}
|
||||
|
||||
+179
-179
@@ -1,179 +1,179 @@
|
||||
// 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.
|
||||
|
||||
/// Slatepack Output 'plugin' implementation
|
||||
use std::fs::{metadata, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::libwallet::{slatepack, Error, Slate, Slatepack, SlatepackBin, Slatepacker};
|
||||
use crate::{SlateGetter, SlatePutter};
|
||||
use grin_wallet_util::byte_ser;
|
||||
|
||||
// And Slate putter impls to output to files
|
||||
pub struct PathToSlatepack<'a> {
|
||||
pub pathbuf: PathBuf,
|
||||
pub packer: &'a Slatepacker<'a>,
|
||||
pub armor_output: bool,
|
||||
}
|
||||
|
||||
impl<'a> PathToSlatepack<'a> {
|
||||
/// Create with pathbuf and recipients
|
||||
pub fn new(pathbuf: PathBuf, packer: &'a Slatepacker<'a>, armor_output: bool) -> Self {
|
||||
Self {
|
||||
pathbuf,
|
||||
packer,
|
||||
armor_output,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_slatepack_file_contents(&self) -> Result<Vec<u8>, Error> {
|
||||
let metadata = metadata(&self.pathbuf)?;
|
||||
let len = metadata.len();
|
||||
let min_len = slatepack::min_size();
|
||||
let max_len = slatepack::max_size();
|
||||
if len < min_len || len > max_len {
|
||||
let msg = format!(
|
||||
"Data is invalid length: {} | min: {}, max: {} |",
|
||||
len, min_len, max_len
|
||||
);
|
||||
return Err(Error::SlatepackDeser(msg));
|
||||
}
|
||||
let mut pub_tx_f = File::open(&self.pathbuf)?;
|
||||
let mut data = Vec::new();
|
||||
pub_tx_f.read_to_end(&mut data)?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub fn get_slatepack(&self, decrypt: bool) -> Result<Slatepack, Error> {
|
||||
let data = self.get_slatepack_file_contents()?;
|
||||
self.packer.deser_slatepack(&data, decrypt)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SlatePutter for PathToSlatepack<'a> {
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> {
|
||||
let slatepack = self.packer.create_slatepack(slate)?;
|
||||
let mut pub_tx = File::create(&self.pathbuf)?;
|
||||
if as_bin {
|
||||
if self.armor_output {
|
||||
let armored = self.packer.armor_slatepack(&slatepack)?;
|
||||
pub_tx.write_all(armored.as_bytes())?;
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
&byte_ser::to_bytes(&SlatepackBin(slatepack))
|
||||
.map_err(|_| Error::SlatepackSer)?,
|
||||
)?;
|
||||
}
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
serde_json::to_string_pretty(&slatepack)
|
||||
.map_err(|_| Error::SlateSer)?
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
pub_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SlateGetter for PathToSlatepack<'a> {
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error> {
|
||||
let data = self.get_slatepack_file_contents()?;
|
||||
let slatepack = self.packer.deser_slatepack(&data, true)?;
|
||||
Ok((self.packer.get_slate(&slatepack)?, true))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
use grin_core::global;
|
||||
|
||||
fn clean_output_dir(test_dir: &str) {
|
||||
let _ = remove_dir_all::remove_dir_all(test_dir);
|
||||
}
|
||||
|
||||
fn setup(test_dir: &str) {
|
||||
clean_output_dir(test_dir);
|
||||
}
|
||||
|
||||
const SLATEPACK_DIR: &'static str = "target/test_output/slatepack";
|
||||
|
||||
#[test]
|
||||
fn pathbuf_get_file_contents() {
|
||||
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
|
||||
setup(SLATEPACK_DIR);
|
||||
|
||||
fs::create_dir_all(SLATEPACK_DIR).unwrap();
|
||||
let sp_path = PathBuf::from(SLATEPACK_DIR).join("pack_file");
|
||||
|
||||
// set Slatepack file to minimum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::min_size()).unwrap();
|
||||
}
|
||||
|
||||
let args = slatepack::SlatepackerArgs {
|
||||
sender: None,
|
||||
recipients: vec![],
|
||||
dec_key: None,
|
||||
};
|
||||
let packer = Slatepacker::new(args);
|
||||
|
||||
let mut pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
// set Slatepack file to maximum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::max_size()).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
// set Slatepack file below minimum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::min_size() - 1).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
// set Slatepack file above maximum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::max_size() + 1).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
/// Slatepack Output 'plugin' implementation
|
||||
use std::fs::{metadata, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::libwallet::{slatepack, Error, Slate, Slatepack, SlatepackBin, Slatepacker};
|
||||
use crate::{SlateGetter, SlatePutter};
|
||||
use grin_wallet_util::byte_ser;
|
||||
|
||||
// And Slate putter impls to output to files
|
||||
pub struct PathToSlatepack<'a> {
|
||||
pub pathbuf: PathBuf,
|
||||
pub packer: &'a Slatepacker<'a>,
|
||||
pub armor_output: bool,
|
||||
}
|
||||
|
||||
impl<'a> PathToSlatepack<'a> {
|
||||
/// Create with pathbuf and recipients
|
||||
pub fn new(pathbuf: PathBuf, packer: &'a Slatepacker<'a>, armor_output: bool) -> Self {
|
||||
Self {
|
||||
pathbuf,
|
||||
packer,
|
||||
armor_output,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_slatepack_file_contents(&self) -> Result<Vec<u8>, Error> {
|
||||
let metadata = metadata(&self.pathbuf)?;
|
||||
let len = metadata.len();
|
||||
let min_len = slatepack::min_size();
|
||||
let max_len = slatepack::max_size();
|
||||
if len < min_len || len > max_len {
|
||||
let msg = format!(
|
||||
"Data is invalid length: {} | min: {}, max: {} |",
|
||||
len, min_len, max_len
|
||||
);
|
||||
return Err(Error::SlatepackDeser(msg));
|
||||
}
|
||||
let mut pub_tx_f = File::open(&self.pathbuf)?;
|
||||
let mut data = Vec::new();
|
||||
pub_tx_f.read_to_end(&mut data)?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub fn get_slatepack(&self, decrypt: bool) -> Result<Slatepack, Error> {
|
||||
let data = self.get_slatepack_file_contents()?;
|
||||
self.packer.deser_slatepack(&data, decrypt)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SlatePutter for PathToSlatepack<'a> {
|
||||
fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> {
|
||||
let slatepack = self.packer.create_slatepack(slate)?;
|
||||
let mut pub_tx = File::create(&self.pathbuf)?;
|
||||
if as_bin {
|
||||
if self.armor_output {
|
||||
let armored = self.packer.armor_slatepack(&slatepack)?;
|
||||
pub_tx.write_all(armored.as_bytes())?;
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
&byte_ser::to_bytes(&SlatepackBin(slatepack))
|
||||
.map_err(|_| Error::SlatepackSer)?,
|
||||
)?;
|
||||
}
|
||||
} else {
|
||||
pub_tx.write_all(
|
||||
serde_json::to_string_pretty(&slatepack)
|
||||
.map_err(|_| Error::SlateSer)?
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
pub_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SlateGetter for PathToSlatepack<'a> {
|
||||
fn get_tx(&self) -> Result<(Slate, bool), Error> {
|
||||
let data = self.get_slatepack_file_contents()?;
|
||||
let slatepack = self.packer.deser_slatepack(&data, true)?;
|
||||
Ok((self.packer.get_slate(&slatepack)?, true))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
use grin_core::global;
|
||||
|
||||
fn clean_output_dir(test_dir: &str) {
|
||||
let _ = remove_dir_all::remove_dir_all(test_dir);
|
||||
}
|
||||
|
||||
fn setup(test_dir: &str) {
|
||||
clean_output_dir(test_dir);
|
||||
}
|
||||
|
||||
const SLATEPACK_DIR: &'static str = "target/test_output/slatepack";
|
||||
|
||||
#[test]
|
||||
fn pathbuf_get_file_contents() {
|
||||
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
|
||||
setup(SLATEPACK_DIR);
|
||||
|
||||
fs::create_dir_all(SLATEPACK_DIR).unwrap();
|
||||
let sp_path = PathBuf::from(SLATEPACK_DIR).join("pack_file");
|
||||
|
||||
// set Slatepack file to minimum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::min_size()).unwrap();
|
||||
}
|
||||
|
||||
let args = slatepack::SlatepackerArgs {
|
||||
sender: None,
|
||||
recipients: vec![],
|
||||
dec_key: None,
|
||||
};
|
||||
let packer = Slatepacker::new(args);
|
||||
|
||||
let mut pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
// set Slatepack file to maximum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::max_size()).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_ok());
|
||||
|
||||
// set Slatepack file below minimum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::min_size() - 1).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
// set Slatepack file above maximum allowable size
|
||||
{
|
||||
let f = File::create(sp_path.clone()).unwrap();
|
||||
f.set_len(slatepack::max_size() + 1).unwrap();
|
||||
}
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
|
||||
pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false);
|
||||
assert!(pack_path.get_slatepack_file_contents().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+767
-767
File diff suppressed because it is too large
Load Diff
+17
-17
@@ -1,17 +1,17 @@
|
||||
// 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 lmdb;
|
||||
|
||||
pub use self::lmdb::{wallet_db_exists, LMDBBackend};
|
||||
// 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 lmdb;
|
||||
|
||||
pub use self::lmdb::{wallet_db_exists, LMDBBackend};
|
||||
|
||||
+289
-289
@@ -1,289 +1,289 @@
|
||||
// Copyright 2018 The Grin Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! High level JSON/HTTP client API
|
||||
|
||||
use crate::util::to_base64;
|
||||
use lazy_static::lazy_static;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
|
||||
use reqwest::{ClientBuilder, Method, Proxy, RequestBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::runtime::{Builder, Handle, Runtime};
|
||||
|
||||
// Global Tokio runtime.
|
||||
// Needs a `Mutex` because `Runtime::block_on` requires mutable access.
|
||||
// Tokio v0.3 requires immutable self, but we are waiting on upstream
|
||||
// updates before we can upgrade.
|
||||
// See: https://github.com/seanmonstar/reqwest/pull/1076
|
||||
lazy_static! {
|
||||
pub static ref RUNTIME: Arc<Mutex<Runtime>> = Arc::new(Mutex::new(
|
||||
Builder::new()
|
||||
.threaded_scheduler()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
));
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Internal error: {0}")]
|
||||
Internal(String),
|
||||
#[error("Bad arguments: {0}")]
|
||||
_Argument(String),
|
||||
#[error("Not found.")]
|
||||
_NotFound,
|
||||
#[error("Request error: {0}")]
|
||||
RequestError(String),
|
||||
#[error("ResponseError error: {0}")]
|
||||
ResponseError(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// New client
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
Self::build(None)
|
||||
}
|
||||
|
||||
pub fn with_socks_proxy(socks_proxy_addr: SocketAddr) -> Result<Self, Error> {
|
||||
Self::build(Some(socks_proxy_addr))
|
||||
}
|
||||
|
||||
fn build(socks_proxy_addr: Option<SocketAddr>) -> Result<Self, Error> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(USER_AGENT, HeaderValue::from_static("grin-client"));
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
|
||||
let mut builder = ClientBuilder::new()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.use_rustls_tls()
|
||||
.default_headers(headers);
|
||||
|
||||
if let Some(s) = socks_proxy_addr {
|
||||
let proxy = Proxy::all(&format!("socks5h://{}:{}", s.ip(), s.port()))
|
||||
.map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
let client = builder
|
||||
.build()
|
||||
.map_err(|e| Error::Internal(format!("Unable to build client: {}", e)))?;
|
||||
|
||||
Ok(Client { client })
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP GET request against a given URL that
|
||||
/// returns a JSON object. Handles request building, JSON deserialization and
|
||||
/// response code checking.
|
||||
pub fn _get<'a, T>(&self, url: &'a str, api_secret: Option<String>) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de>,
|
||||
{
|
||||
self.handle_request(self.build_request(url, Method::GET, api_secret, None)?)
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP GET request against a given
|
||||
/// URL that returns a future. Handles request building, JSON deserialization
|
||||
/// and response code checking.
|
||||
pub async fn _get_async<'a, T>(
|
||||
&self,
|
||||
url: &'a str,
|
||||
api_secret: Option<String>,
|
||||
) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de> + Send + 'static,
|
||||
{
|
||||
self.handle_request_async(self.build_request(url, Method::GET, api_secret, None)?)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP GET request
|
||||
/// on a given URL that returns nothing. Handles request
|
||||
/// building and response code checking.
|
||||
pub fn _get_no_ret(&self, url: &str, api_secret: Option<String>) -> Result<(), Error> {
|
||||
let req = self.build_request(url, Method::GET, api_secret, None)?;
|
||||
self.send_request(req)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP POST request with the provided JSON
|
||||
/// object as body on a given URL that returns a JSON object. Handles request
|
||||
/// building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub fn post<IN, OUT>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<OUT, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
for<'de> OUT: Deserialize<'de>,
|
||||
{
|
||||
let req = self.create_post_request(url, api_secret, input)?;
|
||||
self.handle_request(req)
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP POST request with the
|
||||
/// provided JSON object as body on a given URL that returns a future. Handles
|
||||
/// request building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub async fn post_async<IN, OUT>(
|
||||
&self,
|
||||
url: &str,
|
||||
input: &IN,
|
||||
api_secret: Option<String>,
|
||||
) -> Result<OUT, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
OUT: Send + 'static,
|
||||
for<'de> OUT: Deserialize<'de>,
|
||||
{
|
||||
self.handle_request_async(self.create_post_request(url, api_secret, input)?)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP POST request with the provided JSON
|
||||
/// object as body on a given URL that returns nothing. Handles request
|
||||
/// building, JSON serialization, and response code
|
||||
/// checking.
|
||||
pub fn _post_no_ret<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let req = self.create_post_request(url, api_secret, input)?;
|
||||
self.send_request(req)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP POST request with the
|
||||
/// provided JSON object as body on a given URL that returns a future. Handles
|
||||
/// request building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub async fn _post_no_ret_async<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
self.send_request_async(self.create_post_request(url, api_secret, input)?)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_request(
|
||||
&self,
|
||||
url: &str,
|
||||
method: Method,
|
||||
api_secret: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<RequestBuilder, Error> {
|
||||
let mut builder = self.client.request(method, url);
|
||||
if let Some(api_secret) = api_secret {
|
||||
let basic_auth = format!("Basic {}", to_base64(&format!("grin:{}", api_secret)));
|
||||
builder = builder.header(AUTHORIZATION, basic_auth);
|
||||
}
|
||||
|
||||
if let Some(body) = body {
|
||||
builder = builder.body(body);
|
||||
}
|
||||
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub fn create_post_request<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<RequestBuilder, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let json = serde_json::to_string(input)
|
||||
.map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?;
|
||||
self.build_request(url, Method::POST, api_secret, Some(json))
|
||||
}
|
||||
|
||||
fn handle_request<T>(&self, req: RequestBuilder) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de>,
|
||||
{
|
||||
let data = self.send_request(req)?;
|
||||
serde_json::from_str(&data)
|
||||
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))
|
||||
}
|
||||
|
||||
async fn handle_request_async<T>(&self, req: RequestBuilder) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de> + Send + 'static,
|
||||
{
|
||||
let data = self.send_request_async(req).await?;
|
||||
let ser = serde_json::from_str(&data)
|
||||
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?;
|
||||
Ok(ser)
|
||||
}
|
||||
|
||||
async fn send_request_async(&self, req: RequestBuilder) -> Result<String, Error> {
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?;
|
||||
let text = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn send_request(&self, req: RequestBuilder) -> Result<String, Error> {
|
||||
// This client is currently used both outside and inside of a tokio runtime
|
||||
// context. In the latter case we are not allowed to do a blocking call to
|
||||
// our global runtime, which unfortunately means we have to spawn a new thread
|
||||
if Handle::try_current().is_ok() {
|
||||
let rt = RUNTIME.clone();
|
||||
let client = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
rt.lock()
|
||||
.unwrap()
|
||||
.block_on(async { client.send_request_async(req).await })
|
||||
})
|
||||
.join()
|
||||
.unwrap()
|
||||
} else {
|
||||
RUNTIME
|
||||
.lock()
|
||||
.unwrap()
|
||||
.block_on(self.send_request_async(req))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Copyright 2018 The Grin Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! High level JSON/HTTP client API
|
||||
|
||||
use crate::util::to_base64;
|
||||
use lazy_static::lazy_static;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
|
||||
use reqwest::{ClientBuilder, Method, Proxy, RequestBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::runtime::{Builder, Handle, Runtime};
|
||||
|
||||
// Global Tokio runtime.
|
||||
// Needs a `Mutex` because `Runtime::block_on` requires mutable access.
|
||||
// Tokio v0.3 requires immutable self, but we are waiting on upstream
|
||||
// updates before we can upgrade.
|
||||
// See: https://github.com/seanmonstar/reqwest/pull/1076
|
||||
lazy_static! {
|
||||
pub static ref RUNTIME: Arc<Mutex<Runtime>> = Arc::new(Mutex::new(
|
||||
Builder::new()
|
||||
.threaded_scheduler()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
));
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Internal error: {0}")]
|
||||
Internal(String),
|
||||
#[error("Bad arguments: {0}")]
|
||||
_Argument(String),
|
||||
#[error("Not found.")]
|
||||
_NotFound,
|
||||
#[error("Request error: {0}")]
|
||||
RequestError(String),
|
||||
#[error("ResponseError error: {0}")]
|
||||
ResponseError(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// New client
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
Self::build(None)
|
||||
}
|
||||
|
||||
pub fn with_socks_proxy(socks_proxy_addr: SocketAddr) -> Result<Self, Error> {
|
||||
Self::build(Some(socks_proxy_addr))
|
||||
}
|
||||
|
||||
fn build(socks_proxy_addr: Option<SocketAddr>) -> Result<Self, Error> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(USER_AGENT, HeaderValue::from_static("grin-client"));
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
|
||||
let mut builder = ClientBuilder::new()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.use_rustls_tls()
|
||||
.default_headers(headers);
|
||||
|
||||
if let Some(s) = socks_proxy_addr {
|
||||
let proxy = Proxy::all(&format!("socks5h://{}:{}", s.ip(), s.port()))
|
||||
.map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
let client = builder
|
||||
.build()
|
||||
.map_err(|e| Error::Internal(format!("Unable to build client: {}", e)))?;
|
||||
|
||||
Ok(Client { client })
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP GET request against a given URL that
|
||||
/// returns a JSON object. Handles request building, JSON deserialization and
|
||||
/// response code checking.
|
||||
pub fn _get<'a, T>(&self, url: &'a str, api_secret: Option<String>) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de>,
|
||||
{
|
||||
self.handle_request(self.build_request(url, Method::GET, api_secret, None)?)
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP GET request against a given
|
||||
/// URL that returns a future. Handles request building, JSON deserialization
|
||||
/// and response code checking.
|
||||
pub async fn _get_async<'a, T>(
|
||||
&self,
|
||||
url: &'a str,
|
||||
api_secret: Option<String>,
|
||||
) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de> + Send + 'static,
|
||||
{
|
||||
self.handle_request_async(self.build_request(url, Method::GET, api_secret, None)?)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP GET request
|
||||
/// on a given URL that returns nothing. Handles request
|
||||
/// building and response code checking.
|
||||
pub fn _get_no_ret(&self, url: &str, api_secret: Option<String>) -> Result<(), Error> {
|
||||
let req = self.build_request(url, Method::GET, api_secret, None)?;
|
||||
self.send_request(req)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP POST request with the provided JSON
|
||||
/// object as body on a given URL that returns a JSON object. Handles request
|
||||
/// building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub fn post<IN, OUT>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<OUT, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
for<'de> OUT: Deserialize<'de>,
|
||||
{
|
||||
let req = self.create_post_request(url, api_secret, input)?;
|
||||
self.handle_request(req)
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP POST request with the
|
||||
/// provided JSON object as body on a given URL that returns a future. Handles
|
||||
/// request building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub async fn post_async<IN, OUT>(
|
||||
&self,
|
||||
url: &str,
|
||||
input: &IN,
|
||||
api_secret: Option<String>,
|
||||
) -> Result<OUT, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
OUT: Send + 'static,
|
||||
for<'de> OUT: Deserialize<'de>,
|
||||
{
|
||||
self.handle_request_async(self.create_post_request(url, api_secret, input)?)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Helper function to easily issue a HTTP POST request with the provided JSON
|
||||
/// object as body on a given URL that returns nothing. Handles request
|
||||
/// building, JSON serialization, and response code
|
||||
/// checking.
|
||||
pub fn _post_no_ret<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let req = self.create_post_request(url, api_secret, input)?;
|
||||
self.send_request(req)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper function to easily issue an async HTTP POST request with the
|
||||
/// provided JSON object as body on a given URL that returns a future. Handles
|
||||
/// request building, JSON serialization and deserialization, and response code
|
||||
/// checking.
|
||||
pub async fn _post_no_ret_async<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
self.send_request_async(self.create_post_request(url, api_secret, input)?)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_request(
|
||||
&self,
|
||||
url: &str,
|
||||
method: Method,
|
||||
api_secret: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<RequestBuilder, Error> {
|
||||
let mut builder = self.client.request(method, url);
|
||||
if let Some(api_secret) = api_secret {
|
||||
let basic_auth = format!("Basic {}", to_base64(&format!("grin:{}", api_secret)));
|
||||
builder = builder.header(AUTHORIZATION, basic_auth);
|
||||
}
|
||||
|
||||
if let Some(body) = body {
|
||||
builder = builder.body(body);
|
||||
}
|
||||
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub fn create_post_request<IN>(
|
||||
&self,
|
||||
url: &str,
|
||||
api_secret: Option<String>,
|
||||
input: &IN,
|
||||
) -> Result<RequestBuilder, Error>
|
||||
where
|
||||
IN: Serialize,
|
||||
{
|
||||
let json = serde_json::to_string(input)
|
||||
.map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?;
|
||||
self.build_request(url, Method::POST, api_secret, Some(json))
|
||||
}
|
||||
|
||||
fn handle_request<T>(&self, req: RequestBuilder) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de>,
|
||||
{
|
||||
let data = self.send_request(req)?;
|
||||
serde_json::from_str(&data)
|
||||
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))
|
||||
}
|
||||
|
||||
async fn handle_request_async<T>(&self, req: RequestBuilder) -> Result<T, Error>
|
||||
where
|
||||
for<'de> T: Deserialize<'de> + Send + 'static,
|
||||
{
|
||||
let data = self.send_request_async(req).await?;
|
||||
let ser = serde_json::from_str(&data)
|
||||
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?;
|
||||
Ok(ser)
|
||||
}
|
||||
|
||||
async fn send_request_async(&self, req: RequestBuilder) -> Result<String, Error> {
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?;
|
||||
let text = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn send_request(&self, req: RequestBuilder) -> Result<String, Error> {
|
||||
// This client is currently used both outside and inside of a tokio runtime
|
||||
// context. In the latter case we are not allowed to do a blocking call to
|
||||
// our global runtime, which unfortunately means we have to spawn a new thread
|
||||
if Handle::try_current().is_ok() {
|
||||
let rt = RUNTIME.clone();
|
||||
let client = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
rt.lock()
|
||||
.unwrap()
|
||||
.block_on(async { client.send_request_async(req).await })
|
||||
})
|
||||
.join()
|
||||
.unwrap()
|
||||
} else {
|
||||
RUNTIME
|
||||
.lock()
|
||||
.unwrap()
|
||||
.block_on(self.send_request_async(req))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+264
-264
@@ -1,264 +1,264 @@
|
||||
// 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.
|
||||
// Derived from https://github.com/apoelstra/rust-jsonrpc
|
||||
|
||||
//! JSON RPC Client functionality
|
||||
use std::{error, fmt};
|
||||
|
||||
use serde_json;
|
||||
|
||||
/// Builds a request
|
||||
pub fn build_request<'a, 'b>(name: &'a str, params: &'b serde_json::Value) -> Request<'a, 'b> {
|
||||
Request {
|
||||
method: name,
|
||||
params: params,
|
||||
id: From::from(1),
|
||||
jsonrpc: Some("2.0"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
/// A JSONRPC request object
|
||||
pub struct Request<'a, 'b> {
|
||||
/// The name of the RPC call
|
||||
pub method: &'a str,
|
||||
/// Parameters to the RPC call
|
||||
pub params: &'b serde_json::Value,
|
||||
/// Identifier for this Request, which should appear in the response
|
||||
pub id: serde_json::Value,
|
||||
/// jsonrpc field, MUST be "2.0"
|
||||
pub jsonrpc: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
/// A JSONRPC response object
|
||||
pub struct Response {
|
||||
/// A result if there is one, or null
|
||||
pub result: Option<serde_json::Value>,
|
||||
/// An error if there is one, or null
|
||||
pub error: Option<RpcError>,
|
||||
/// Identifier for this Request, which should match that of the request
|
||||
pub id: serde_json::Value,
|
||||
/// jsonrpc field, MUST be "2.0"
|
||||
pub jsonrpc: Option<String>,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
/// Extract the result from a response
|
||||
pub fn result<T: serde::de::DeserializeOwned>(&self) -> Result<T, Error> {
|
||||
if let Some(ref e) = self.error {
|
||||
return Err(Error::Rpc(e.clone()));
|
||||
}
|
||||
|
||||
let result = match self.result.clone() {
|
||||
Some(r) => serde_json::from_value(r["Ok"].clone()).map_err(Error::Json),
|
||||
None => serde_json::from_value(serde_json::Value::Null).map_err(Error::Json),
|
||||
}?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Extract the result from a response, consuming the response
|
||||
pub fn into_result<T: serde::de::DeserializeOwned>(self) -> Result<T, Error> {
|
||||
if let Some(e) = self.error {
|
||||
return Err(Error::Rpc(e));
|
||||
}
|
||||
self.result()
|
||||
}
|
||||
|
||||
/// Return the RPC error, if there was one, but do not check the result
|
||||
pub fn _check_error(self) -> Result<(), Error> {
|
||||
if let Some(e) = self.error {
|
||||
Err(Error::Rpc(e))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether or not the `result` field is empty
|
||||
pub fn _is_none(&self) -> bool {
|
||||
self.result.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// A library error
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// Json error
|
||||
Json(serde_json::Error),
|
||||
/// Error response
|
||||
Rpc(RpcError),
|
||||
/// Response to a request did not have the expected nonce
|
||||
_NonceMismatch,
|
||||
/// Response to a request had a jsonrpc field other than "2.0"
|
||||
_VersionMismatch,
|
||||
/// Batches can't be empty
|
||||
_EmptyBatch,
|
||||
/// Too many responses returned in batch
|
||||
_WrongBatchResponseSize,
|
||||
/// Batch response contained a duplicate ID
|
||||
_BatchDuplicateResponseId(serde_json::Value),
|
||||
/// Batch response contained an ID that didn't correspond to any request ID
|
||||
_WrongBatchResponseId(serde_json::Value),
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(e: serde_json::Error) -> Error {
|
||||
Error::Json(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RpcError> for Error {
|
||||
fn from(e: RpcError) -> Error {
|
||||
Error::Rpc(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Error::Json(ref e) => write!(f, "JSON decode error: {}", e),
|
||||
Error::Rpc(ref r) => write!(f, "RPC error response: {:?}", r),
|
||||
Error::_BatchDuplicateResponseId(ref v) => {
|
||||
write!(f, "duplicate RPC batch response ID: {}", v)
|
||||
}
|
||||
Error::_WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v),
|
||||
ref e => f.write_str(&format!("{}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
Error::Json(_) => "JSON decode error",
|
||||
Error::Rpc(_) => "RPC error response",
|
||||
Error::_NonceMismatch => "Nonce of response did not match nonce of request",
|
||||
Error::_VersionMismatch => "`jsonrpc` field set to non-\"2.0\"",
|
||||
Error::_EmptyBatch => "batches can't be empty",
|
||||
Error::_WrongBatchResponseSize => "too many responses returned in batch",
|
||||
Error::_BatchDuplicateResponseId(_) => "batch response contained a duplicate ID",
|
||||
Error::_WrongBatchResponseId(_) => {
|
||||
"batch response contained an ID that didn't correspond to any request ID"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&dyn error::Error> {
|
||||
match *self {
|
||||
Error::Json(ref e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Standard error responses, as described at at
|
||||
/// http://www.jsonrpc.org/specification#error_object
|
||||
///
|
||||
/// # Documentation Copyright
|
||||
/// Copyright (C) 2007-2010 by the JSON-RPC Working Group
|
||||
///
|
||||
/// This document and translations of it may be used to implement JSON-RPC, it
|
||||
/// may be copied and furnished to others, and derivative works that comment
|
||||
/// on or otherwise explain it or assist in its implementation may be prepared,
|
||||
/// copied, published and distributed, in whole or in part, without restriction
|
||||
/// of any kind, provided that the above copyright notice and this paragraph
|
||||
/// are included on all such copies and derivative works. However, this document
|
||||
/// itself may not be modified in any way.
|
||||
///
|
||||
/// The limited permissions granted above are perpetual and will not be revoked.
|
||||
///
|
||||
/// This document and the information contained herein is provided "AS IS" and
|
||||
/// ALL WARRANTIES, EXPRESS OR IMPLIED are DISCLAIMED, INCLUDING BUT NOT LIMITED
|
||||
/// TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
|
||||
/// RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
|
||||
/// PARTICULAR PURPOSE.
|
||||
///
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum StandardError {
|
||||
/// Invalid JSON was received by the server.
|
||||
/// An error occurred on the server while parsing the JSON text.
|
||||
ParseError,
|
||||
/// The JSON sent is not a valid Request object.
|
||||
InvalidRequest,
|
||||
/// The method does not exist / is not available.
|
||||
MethodNotFound,
|
||||
/// Invalid method parameter(s).
|
||||
InvalidParams,
|
||||
/// Internal JSON-RPC error.
|
||||
InternalError,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
/// A JSONRPC error object
|
||||
pub struct RpcError {
|
||||
/// The integer identifier of the error
|
||||
pub code: i32,
|
||||
/// A string describing the error
|
||||
pub message: String,
|
||||
/// Additional data specific to the error
|
||||
pub data: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Create a standard error responses
|
||||
pub fn _standard_error(code: StandardError, data: Option<serde_json::Value>) -> RpcError {
|
||||
match code {
|
||||
StandardError::ParseError => RpcError {
|
||||
code: -32700,
|
||||
message: "Parse error".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InvalidRequest => RpcError {
|
||||
code: -32600,
|
||||
message: "Invalid Request".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::MethodNotFound => RpcError {
|
||||
code: -32601,
|
||||
message: "Method not found".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InvalidParams => RpcError {
|
||||
code: -32602,
|
||||
message: "Invalid params".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InternalError => RpcError {
|
||||
code: -32603,
|
||||
message: "Internal error".to_string(),
|
||||
data: data,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a Rust `Result` to a JSONRPC response object
|
||||
pub fn _result_to_response(
|
||||
result: Result<serde_json::Value, RpcError>,
|
||||
id: serde_json::Value,
|
||||
) -> Response {
|
||||
match result {
|
||||
Ok(data) => Response {
|
||||
result: Some(data),
|
||||
error: None,
|
||||
id: id,
|
||||
jsonrpc: Some(String::from("2.0")),
|
||||
},
|
||||
Err(err) => Response {
|
||||
result: None,
|
||||
error: Some(err),
|
||||
id: id,
|
||||
jsonrpc: Some(String::from("2.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.
|
||||
// Derived from https://github.com/apoelstra/rust-jsonrpc
|
||||
|
||||
//! JSON RPC Client functionality
|
||||
use std::{error, fmt};
|
||||
|
||||
use serde_json;
|
||||
|
||||
/// Builds a request
|
||||
pub fn build_request<'a, 'b>(name: &'a str, params: &'b serde_json::Value) -> Request<'a, 'b> {
|
||||
Request {
|
||||
method: name,
|
||||
params: params,
|
||||
id: From::from(1),
|
||||
jsonrpc: Some("2.0"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
/// A JSONRPC request object
|
||||
pub struct Request<'a, 'b> {
|
||||
/// The name of the RPC call
|
||||
pub method: &'a str,
|
||||
/// Parameters to the RPC call
|
||||
pub params: &'b serde_json::Value,
|
||||
/// Identifier for this Request, which should appear in the response
|
||||
pub id: serde_json::Value,
|
||||
/// jsonrpc field, MUST be "2.0"
|
||||
pub jsonrpc: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
/// A JSONRPC response object
|
||||
pub struct Response {
|
||||
/// A result if there is one, or null
|
||||
pub result: Option<serde_json::Value>,
|
||||
/// An error if there is one, or null
|
||||
pub error: Option<RpcError>,
|
||||
/// Identifier for this Request, which should match that of the request
|
||||
pub id: serde_json::Value,
|
||||
/// jsonrpc field, MUST be "2.0"
|
||||
pub jsonrpc: Option<String>,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
/// Extract the result from a response
|
||||
pub fn result<T: serde::de::DeserializeOwned>(&self) -> Result<T, Error> {
|
||||
if let Some(ref e) = self.error {
|
||||
return Err(Error::Rpc(e.clone()));
|
||||
}
|
||||
|
||||
let result = match self.result.clone() {
|
||||
Some(r) => serde_json::from_value(r["Ok"].clone()).map_err(Error::Json),
|
||||
None => serde_json::from_value(serde_json::Value::Null).map_err(Error::Json),
|
||||
}?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Extract the result from a response, consuming the response
|
||||
pub fn into_result<T: serde::de::DeserializeOwned>(self) -> Result<T, Error> {
|
||||
if let Some(e) = self.error {
|
||||
return Err(Error::Rpc(e));
|
||||
}
|
||||
self.result()
|
||||
}
|
||||
|
||||
/// Return the RPC error, if there was one, but do not check the result
|
||||
pub fn _check_error(self) -> Result<(), Error> {
|
||||
if let Some(e) = self.error {
|
||||
Err(Error::Rpc(e))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether or not the `result` field is empty
|
||||
pub fn _is_none(&self) -> bool {
|
||||
self.result.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// A library error
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// Json error
|
||||
Json(serde_json::Error),
|
||||
/// Error response
|
||||
Rpc(RpcError),
|
||||
/// Response to a request did not have the expected nonce
|
||||
_NonceMismatch,
|
||||
/// Response to a request had a jsonrpc field other than "2.0"
|
||||
_VersionMismatch,
|
||||
/// Batches can't be empty
|
||||
_EmptyBatch,
|
||||
/// Too many responses returned in batch
|
||||
_WrongBatchResponseSize,
|
||||
/// Batch response contained a duplicate ID
|
||||
_BatchDuplicateResponseId(serde_json::Value),
|
||||
/// Batch response contained an ID that didn't correspond to any request ID
|
||||
_WrongBatchResponseId(serde_json::Value),
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(e: serde_json::Error) -> Error {
|
||||
Error::Json(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RpcError> for Error {
|
||||
fn from(e: RpcError) -> Error {
|
||||
Error::Rpc(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Error::Json(ref e) => write!(f, "JSON decode error: {}", e),
|
||||
Error::Rpc(ref r) => write!(f, "RPC error response: {:?}", r),
|
||||
Error::_BatchDuplicateResponseId(ref v) => {
|
||||
write!(f, "duplicate RPC batch response ID: {}", v)
|
||||
}
|
||||
Error::_WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v),
|
||||
ref e => f.write_str(&format!("{}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
Error::Json(_) => "JSON decode error",
|
||||
Error::Rpc(_) => "RPC error response",
|
||||
Error::_NonceMismatch => "Nonce of response did not match nonce of request",
|
||||
Error::_VersionMismatch => "`jsonrpc` field set to non-\"2.0\"",
|
||||
Error::_EmptyBatch => "batches can't be empty",
|
||||
Error::_WrongBatchResponseSize => "too many responses returned in batch",
|
||||
Error::_BatchDuplicateResponseId(_) => "batch response contained a duplicate ID",
|
||||
Error::_WrongBatchResponseId(_) => {
|
||||
"batch response contained an ID that didn't correspond to any request ID"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&dyn error::Error> {
|
||||
match *self {
|
||||
Error::Json(ref e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Standard error responses, as described at at
|
||||
/// http://www.jsonrpc.org/specification#error_object
|
||||
///
|
||||
/// # Documentation Copyright
|
||||
/// Copyright (C) 2007-2010 by the JSON-RPC Working Group
|
||||
///
|
||||
/// This document and translations of it may be used to implement JSON-RPC, it
|
||||
/// may be copied and furnished to others, and derivative works that comment
|
||||
/// on or otherwise explain it or assist in its implementation may be prepared,
|
||||
/// copied, published and distributed, in whole or in part, without restriction
|
||||
/// of any kind, provided that the above copyright notice and this paragraph
|
||||
/// are included on all such copies and derivative works. However, this document
|
||||
/// itself may not be modified in any way.
|
||||
///
|
||||
/// The limited permissions granted above are perpetual and will not be revoked.
|
||||
///
|
||||
/// This document and the information contained herein is provided "AS IS" and
|
||||
/// ALL WARRANTIES, EXPRESS OR IMPLIED are DISCLAIMED, INCLUDING BUT NOT LIMITED
|
||||
/// TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
|
||||
/// RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
|
||||
/// PARTICULAR PURPOSE.
|
||||
///
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum StandardError {
|
||||
/// Invalid JSON was received by the server.
|
||||
/// An error occurred on the server while parsing the JSON text.
|
||||
ParseError,
|
||||
/// The JSON sent is not a valid Request object.
|
||||
InvalidRequest,
|
||||
/// The method does not exist / is not available.
|
||||
MethodNotFound,
|
||||
/// Invalid method parameter(s).
|
||||
InvalidParams,
|
||||
/// Internal JSON-RPC error.
|
||||
InternalError,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
/// A JSONRPC error object
|
||||
pub struct RpcError {
|
||||
/// The integer identifier of the error
|
||||
pub code: i32,
|
||||
/// A string describing the error
|
||||
pub message: String,
|
||||
/// Additional data specific to the error
|
||||
pub data: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Create a standard error responses
|
||||
pub fn _standard_error(code: StandardError, data: Option<serde_json::Value>) -> RpcError {
|
||||
match code {
|
||||
StandardError::ParseError => RpcError {
|
||||
code: -32700,
|
||||
message: "Parse error".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InvalidRequest => RpcError {
|
||||
code: -32600,
|
||||
message: "Invalid Request".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::MethodNotFound => RpcError {
|
||||
code: -32601,
|
||||
message: "Method not found".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InvalidParams => RpcError {
|
||||
code: -32602,
|
||||
message: "Invalid params".to_string(),
|
||||
data: data,
|
||||
},
|
||||
StandardError::InternalError => RpcError {
|
||||
code: -32603,
|
||||
message: "Internal error".to_string(),
|
||||
data: data,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a Rust `Result` to a JSONRPC response object
|
||||
pub fn _result_to_response(
|
||||
result: Result<serde_json::Value, RpcError>,
|
||||
id: serde_json::Value,
|
||||
) -> Response {
|
||||
match result {
|
||||
Ok(data) => Response {
|
||||
result: Some(data),
|
||||
error: None,
|
||||
id: id,
|
||||
jsonrpc: Some(String::from("2.0")),
|
||||
},
|
||||
Err(err) => Response {
|
||||
result: None,
|
||||
error: Some(err),
|
||||
id: id,
|
||||
jsonrpc: Some(String::from("2.0")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
// 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 client;
|
||||
pub mod json_rpc;
|
||||
|
||||
pub use client::{Client, Error as ClientError, RUNTIME};
|
||||
// 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 client;
|
||||
pub mod json_rpc;
|
||||
|
||||
pub use client::{Client, Error as ClientError, RUNTIME};
|
||||
|
||||
+104
-104
@@ -1,104 +1,104 @@
|
||||
// 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.
|
||||
|
||||
//! Implementation specific error types
|
||||
use crate::core::libtx;
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use crate::util::secp;
|
||||
use grin_wallet_util::OnionV3AddressError;
|
||||
|
||||
/// Wallet errors, mostly wrappers around underlying crypto or I/O errors.
|
||||
#[derive(Clone, thiserror::Error, Eq, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
/// LibTX Error
|
||||
#[error("LibTx Error")]
|
||||
LibTX(#[from] libtx::Error),
|
||||
|
||||
/// LibWallet Error
|
||||
#[error("LibWallet Error: {0}")]
|
||||
LibWallet(#[from] libwallet::Error),
|
||||
|
||||
/// Keychain error
|
||||
#[error("Keychain error")]
|
||||
Keychain(#[from] keychain::Error),
|
||||
|
||||
/// Onion V3 Address Error
|
||||
#[error("Onion V3 Address Error")]
|
||||
OnionV3Address(#[from] OnionV3AddressError),
|
||||
|
||||
/// Error when obfs4proxy is not in the user path if TOR brigde is enabled
|
||||
#[error("Unable to find obfs4proxy binary in your path; {}", _0)]
|
||||
Obfs4proxyBin(String),
|
||||
|
||||
/// Error the bridge input is in bad format
|
||||
#[error("Bridge line is in bad format; {}", _0)]
|
||||
BridgeLine(String),
|
||||
|
||||
/// Error when formatting json
|
||||
#[error("IO error")]
|
||||
IO,
|
||||
|
||||
/// Secp Error
|
||||
#[error("Secp error")]
|
||||
Secp(#[from] secp::Error),
|
||||
|
||||
/// Error when formatting json
|
||||
#[error("Serde JSON error")]
|
||||
Format,
|
||||
|
||||
/// Wallet seed already exists
|
||||
#[error("Wallet seed file exists: {}", _0)]
|
||||
WalletSeedExists(String),
|
||||
|
||||
/// Wallet seed doesn't exist
|
||||
#[error("Wallet seed doesn't exist error")]
|
||||
WalletSeedDoesntExist,
|
||||
|
||||
/// Wallet seed doesn't exist
|
||||
#[error("Wallet doesn't exist at {}. {}", _0, _1)]
|
||||
WalletDoesntExist(String, String),
|
||||
|
||||
/// Enc/Decryption Error
|
||||
#[error("Enc/Decryption error (check password?)")]
|
||||
Encryption,
|
||||
|
||||
/// BIP 39 word list
|
||||
#[error("BIP39 Mnemonic (word list) Error")]
|
||||
Mnemonic,
|
||||
|
||||
/// Command line argument error
|
||||
#[error("{}", _0)]
|
||||
ArgumentError(String),
|
||||
|
||||
/// Tor Bridge error
|
||||
#[error("Tor Bridge Error: {}", _0)]
|
||||
TorBridge(String),
|
||||
|
||||
/// Tor Proxy error
|
||||
#[error("Tor Proxy Error: {}", _0)]
|
||||
TorProxy(String),
|
||||
|
||||
/// Generating ED25519 Public Key
|
||||
#[error("Error generating ed25519 secret key: {}", _0)]
|
||||
ED25519Key(String),
|
||||
|
||||
/// Checking for onion address
|
||||
#[error("Address is not an Onion v3 Address: {}", _0)]
|
||||
NotOnion(String),
|
||||
|
||||
/// Other
|
||||
#[error("Generic error: {}", _0)]
|
||||
GenericError(String),
|
||||
}
|
||||
// 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.
|
||||
|
||||
//! Implementation specific error types
|
||||
use crate::core::libtx;
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use crate::util::secp;
|
||||
use grin_wallet_util::OnionV3AddressError;
|
||||
|
||||
/// Wallet errors, mostly wrappers around underlying crypto or I/O errors.
|
||||
#[derive(Clone, thiserror::Error, Eq, PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
/// LibTX Error
|
||||
#[error("LibTx Error")]
|
||||
LibTX(#[from] libtx::Error),
|
||||
|
||||
/// LibWallet Error
|
||||
#[error("LibWallet Error: {0}")]
|
||||
LibWallet(#[from] libwallet::Error),
|
||||
|
||||
/// Keychain error
|
||||
#[error("Keychain error")]
|
||||
Keychain(#[from] keychain::Error),
|
||||
|
||||
/// Onion V3 Address Error
|
||||
#[error("Onion V3 Address Error")]
|
||||
OnionV3Address(#[from] OnionV3AddressError),
|
||||
|
||||
/// Error when obfs4proxy is not in the user path if TOR brigde is enabled
|
||||
#[error("Unable to find obfs4proxy binary in your path; {}", _0)]
|
||||
Obfs4proxyBin(String),
|
||||
|
||||
/// Error the bridge input is in bad format
|
||||
#[error("Bridge line is in bad format; {}", _0)]
|
||||
BridgeLine(String),
|
||||
|
||||
/// Error when formatting json
|
||||
#[error("IO error")]
|
||||
IO,
|
||||
|
||||
/// Secp Error
|
||||
#[error("Secp error")]
|
||||
Secp(#[from] secp::Error),
|
||||
|
||||
/// Error when formatting json
|
||||
#[error("Serde JSON error")]
|
||||
Format,
|
||||
|
||||
/// Wallet seed already exists
|
||||
#[error("Wallet seed file exists: {}", _0)]
|
||||
WalletSeedExists(String),
|
||||
|
||||
/// Wallet seed doesn't exist
|
||||
#[error("Wallet seed doesn't exist error")]
|
||||
WalletSeedDoesntExist,
|
||||
|
||||
/// Wallet seed doesn't exist
|
||||
#[error("Wallet doesn't exist at {}. {}", _0, _1)]
|
||||
WalletDoesntExist(String, String),
|
||||
|
||||
/// Enc/Decryption Error
|
||||
#[error("Enc/Decryption error (check password?)")]
|
||||
Encryption,
|
||||
|
||||
/// BIP 39 word list
|
||||
#[error("BIP39 Mnemonic (word list) Error")]
|
||||
Mnemonic,
|
||||
|
||||
/// Command line argument error
|
||||
#[error("{}", _0)]
|
||||
ArgumentError(String),
|
||||
|
||||
/// Tor Bridge error
|
||||
#[error("Tor Bridge Error: {}", _0)]
|
||||
TorBridge(String),
|
||||
|
||||
/// Tor Proxy error
|
||||
#[error("Tor Proxy Error: {}", _0)]
|
||||
TorProxy(String),
|
||||
|
||||
/// Generating ED25519 Public Key
|
||||
#[error("Error generating ed25519 secret key: {}", _0)]
|
||||
ED25519Key(String),
|
||||
|
||||
/// Checking for onion address
|
||||
#[error("Address is not an Onion v3 Address: {}", _0)]
|
||||
NotOnion(String),
|
||||
|
||||
/// Other
|
||||
#[error("Generic error: {}", _0)]
|
||||
GenericError(String),
|
||||
}
|
||||
|
||||
+91
-91
@@ -1,91 +1,91 @@
|
||||
// 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.
|
||||
|
||||
//! Concrete implementations of types found in libwallet, organised this
|
||||
//! way mostly to avoid any circular dependencies of any kind
|
||||
//! Functions in this crate should not use the wallet api crate directly
|
||||
|
||||
use blake2_rfc as blake2;
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_store as store;
|
||||
use grin_util as util;
|
||||
use grin_wallet_libwallet as libwallet;
|
||||
|
||||
use grin_wallet_config as config;
|
||||
|
||||
mod adapters;
|
||||
mod backends;
|
||||
mod client_utils;
|
||||
mod error;
|
||||
mod lifecycle;
|
||||
mod node_clients;
|
||||
pub mod test_framework;
|
||||
pub mod tor;
|
||||
|
||||
pub use crate::adapters::{
|
||||
HttpSlateSender, PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver,
|
||||
SlateSender,
|
||||
};
|
||||
pub use crate::backends::{wallet_db_exists, LMDBBackend};
|
||||
pub use crate::error::Error;
|
||||
pub use crate::lifecycle::DefaultLCProvider;
|
||||
pub use crate::node_clients::HTTPNodeClient;
|
||||
|
||||
use crate::keychain::{ExtKeychain, Keychain};
|
||||
|
||||
use libwallet::{NodeClient, WalletInst, WalletLCProvider};
|
||||
|
||||
/// Main wallet instance
|
||||
pub struct DefaultWalletImpl<'a, C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
{
|
||||
lc_provider: DefaultLCProvider<'a, C, ExtKeychain>,
|
||||
}
|
||||
|
||||
impl<'a, C> DefaultWalletImpl<'a, C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
{
|
||||
pub fn new(node_client: C) -> Result<Self, Error> {
|
||||
let lc_provider = DefaultLCProvider::new(node_client);
|
||||
Ok(DefaultWalletImpl {
|
||||
lc_provider: lc_provider,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, L, C, K> WalletInst<'a, L, C, K> for DefaultWalletImpl<'a, C>
|
||||
where
|
||||
DefaultLCProvider<'a, C, ExtKeychain>: WalletLCProvider<'a, C, K>,
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
fn lc_provider(
|
||||
&mut self,
|
||||
) -> Result<&mut (dyn WalletLCProvider<'a, C, K> + 'a), libwallet::Error> {
|
||||
Ok(&mut self.lc_provider)
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
//! Concrete implementations of types found in libwallet, organised this
|
||||
//! way mostly to avoid any circular dependencies of any kind
|
||||
//! Functions in this crate should not use the wallet api crate directly
|
||||
|
||||
use blake2_rfc as blake2;
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_store as store;
|
||||
use grin_util as util;
|
||||
use grin_wallet_libwallet as libwallet;
|
||||
|
||||
use grin_wallet_config as config;
|
||||
|
||||
mod adapters;
|
||||
mod backends;
|
||||
mod client_utils;
|
||||
mod error;
|
||||
mod lifecycle;
|
||||
mod node_clients;
|
||||
pub mod test_framework;
|
||||
pub mod tor;
|
||||
|
||||
pub use crate::adapters::{
|
||||
HttpSlateSender, PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver,
|
||||
SlateSender,
|
||||
};
|
||||
pub use crate::backends::{wallet_db_exists, LMDBBackend};
|
||||
pub use crate::error::Error;
|
||||
pub use crate::lifecycle::DefaultLCProvider;
|
||||
pub use crate::node_clients::HTTPNodeClient;
|
||||
|
||||
use crate::keychain::{ExtKeychain, Keychain};
|
||||
|
||||
use libwallet::{NodeClient, WalletInst, WalletLCProvider};
|
||||
|
||||
/// Main wallet instance
|
||||
pub struct DefaultWalletImpl<'a, C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
{
|
||||
lc_provider: DefaultLCProvider<'a, C, ExtKeychain>,
|
||||
}
|
||||
|
||||
impl<'a, C> DefaultWalletImpl<'a, C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
{
|
||||
pub fn new(node_client: C) -> Result<Self, Error> {
|
||||
let lc_provider = DefaultLCProvider::new(node_client);
|
||||
Ok(DefaultWalletImpl {
|
||||
lc_provider: lc_provider,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, L, C, K> WalletInst<'a, L, C, K> for DefaultWalletImpl<'a, C>
|
||||
where
|
||||
DefaultLCProvider<'a, C, ExtKeychain>: WalletLCProvider<'a, C, K>,
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
fn lc_provider(
|
||||
&mut self,
|
||||
) -> Result<&mut (dyn WalletLCProvider<'a, C, K> + 'a), libwallet::Error> {
|
||||
Ok(&mut self.lc_provider)
|
||||
}
|
||||
}
|
||||
|
||||
+395
-395
@@ -1,395 +1,395 @@
|
||||
// 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.
|
||||
|
||||
//! Default wallet lifecycle provider
|
||||
|
||||
use crate::config::{
|
||||
config, GlobalWalletConfig, GlobalWalletConfigMembers, TorConfig, WalletConfig, GRIN_WALLET_DIR,
|
||||
};
|
||||
use crate::core::global;
|
||||
use crate::keychain::Keychain;
|
||||
use crate::libwallet::{Error, NodeClient, WalletBackend, WalletInitStatus, WalletLCProvider};
|
||||
use crate::lifecycle::seed::WalletSeed;
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::ZeroingString;
|
||||
use crate::LMDBBackend;
|
||||
use grin_util::logger::LoggingConfig;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
|
||||
// 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);
|
||||
let path = path.replace("\\", &sep);
|
||||
path
|
||||
}
|
||||
|
||||
pub struct DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
data_dir: String,
|
||||
node_client: C,
|
||||
backend: Option<Box<dyn WalletBackend<'a, C, K> + 'a>>,
|
||||
}
|
||||
|
||||
impl<'a, C, K> DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
/// Create new provider
|
||||
pub fn new(node_client: C) -> Self {
|
||||
DefaultLCProvider {
|
||||
node_client,
|
||||
data_dir: "default".to_owned(),
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, C, K> WalletLCProvider<'a, C, K> for DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
fn set_top_level_directory(&mut self, dir: &str) -> Result<(), Error> {
|
||||
self.data_dir = dir.to_owned();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_top_level_directory(&self) -> Result<String, Error> {
|
||||
let sep = &MAIN_SEPARATOR.to_string();
|
||||
let data_dir = self
|
||||
.data_dir
|
||||
.to_owned()
|
||||
.replace("/", &sep)
|
||||
.replace("\\", &sep);
|
||||
Ok(data_dir)
|
||||
}
|
||||
|
||||
fn create_config(
|
||||
&self,
|
||||
chain_type: &global::ChainTypes,
|
||||
file_name: &str,
|
||||
wallet_config: Option<WalletConfig>,
|
||||
logging_config: Option<LoggingConfig>,
|
||||
tor_config: Option<TorConfig>,
|
||||
) -> Result<(), Error> {
|
||||
let mut default_config = GlobalWalletConfig::for_chain(&chain_type);
|
||||
let config_file_version = match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().config_file_version,
|
||||
None => None,
|
||||
};
|
||||
let logging = match logging_config {
|
||||
Some(l) => Some(l),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().logging,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
// Check if config was provided, if not load default and set update to "true"
|
||||
let (wallet, update) = match wallet_config {
|
||||
Some(w) => (w, false),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => (m.clone().wallet, true),
|
||||
None => (WalletConfig::default(), true),
|
||||
},
|
||||
};
|
||||
let tor = match tor_config {
|
||||
Some(t) => Some(t),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().tor,
|
||||
None => Some(TorConfig::default()),
|
||||
},
|
||||
};
|
||||
default_config = GlobalWalletConfig {
|
||||
members: Some(GlobalWalletConfigMembers {
|
||||
config_file_version,
|
||||
wallet,
|
||||
tor,
|
||||
logging,
|
||||
}),
|
||||
..default_config
|
||||
};
|
||||
let mut config_file_name = PathBuf::from(self.data_dir.clone());
|
||||
config_file_name.push(file_name);
|
||||
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
|
||||
if config_file_name.exists() && data_dir_name.exists() {
|
||||
let msg = format!(
|
||||
"{} already exists in the target directory ({}). Please remove it first",
|
||||
file_name,
|
||||
config_file_name.to_str().unwrap()
|
||||
);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
|
||||
// If config exists but the datadir return ok
|
||||
if config_file_name.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
// default settings are updated if no config was provided, no support for top_dir/here
|
||||
let mut abs_path_node = std::env::current_dir()?;
|
||||
abs_path_node.push(self.data_dir.clone());
|
||||
let mut absolute_path_wallet = std::env::current_dir()?;
|
||||
absolute_path_wallet.push(self.data_dir.clone());
|
||||
|
||||
// if no config provided, update defaults
|
||||
if update == true {
|
||||
// create top level dir if it doesn't exist
|
||||
let dd = PathBuf::from(self.data_dir.clone());
|
||||
if !dd.exists() {
|
||||
// try create
|
||||
fs::create_dir_all(dd)?;
|
||||
default_config.update_paths(&abs_path_node, &absolute_path_wallet);
|
||||
}
|
||||
};
|
||||
let res =
|
||||
default_config.write_to_file(config_file_name.to_str().unwrap(), false, None, None);
|
||||
if let Err(e) = res {
|
||||
let msg = format!(
|
||||
"Error creating config file as ({}): {}",
|
||||
config_file_name.to_str().unwrap(),
|
||||
e
|
||||
);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
|
||||
info!(
|
||||
"File {} configured and created",
|
||||
config_file_name.to_str().unwrap(),
|
||||
);
|
||||
|
||||
let mut api_secret_path = PathBuf::from(self.data_dir.clone());
|
||||
api_secret_path.push(PathBuf::from(config::API_SECRET_FILE_NAME));
|
||||
if !api_secret_path.exists() {
|
||||
config::init_api_secret(&api_secret_path).unwrap();
|
||||
} else {
|
||||
config::check_api_secret(&api_secret_path).unwrap();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_wallet(
|
||||
&mut self,
|
||||
_name: Option<&str>,
|
||||
mnemonic: Option<ZeroingString>,
|
||||
mnemonic_length: usize,
|
||||
password: ZeroingString,
|
||||
test_mode: bool,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path((data_dir_name.to_str().unwrap()).to_string());
|
||||
let exists = WalletSeed::seed_file_exists(&data_dir_name);
|
||||
if !test_mode {
|
||||
if let Ok(true) = exists {
|
||||
let msg = format!("Wallet seed already exists at4565: {}", data_dir_name);
|
||||
return Err(Error::WalletSeedExists(msg));
|
||||
}
|
||||
}
|
||||
WalletSeed::init_file(
|
||||
&data_dir_name,
|
||||
mnemonic_length,
|
||||
mnemonic.clone(),
|
||||
password,
|
||||
test_mode,
|
||||
)
|
||||
.map_err(|_| {
|
||||
Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned())
|
||||
})?;
|
||||
info!("Wallet seed file created");
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
error!("{}", msg);
|
||||
return Err(Error::Lifecycle(msg).into());
|
||||
}
|
||||
Ok(d) => d,
|
||||
};
|
||||
// Save init status of this wallet, to determine whether it needs a full UTXO scan
|
||||
let mut batch = wallet.batch_no_mask()?;
|
||||
match mnemonic {
|
||||
Some(_) => batch.save_init_status(WalletInitStatus::InitNeedsScanning)?,
|
||||
None => batch.save_init_status(WalletInitStatus::InitNoScanning)?,
|
||||
};
|
||||
batch.commit()?;
|
||||
info!("Wallet database backend created at {}", data_dir_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_wallet(
|
||||
&mut self,
|
||||
_name: Option<&str>,
|
||||
password: ZeroingString,
|
||||
create_mask: bool,
|
||||
use_test_rng: bool,
|
||||
) -> Result<Option<SecretKey>, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path(data_dir_name.to_str().unwrap().to_string());
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
Ok(d) => d,
|
||||
};
|
||||
let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| {
|
||||
Error::Lifecycle("Error opening wallet (is password correct?)".to_owned())
|
||||
})?;
|
||||
let keychain = wallet_seed
|
||||
.derive_keychain(global::is_testnet())
|
||||
.map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?;
|
||||
|
||||
let mask = wallet.set_keychain(Box::new(keychain), create_mask, use_test_rng)?;
|
||||
self.backend = Some(Box::new(wallet));
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
fn close_wallet(&mut self, _name: Option<&str>) -> Result<(), Error> {
|
||||
if let Some(b) = self.backend.as_mut() {
|
||||
b.close()?
|
||||
}
|
||||
self.backend = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wallet_exists(&self, _name: Option<&str>) -> Result<bool, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
let res = WalletSeed::seed_file_exists(&data_dir_name)
|
||||
.map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn get_mnemonic(
|
||||
&self,
|
||||
_name: Option<&str>,
|
||||
password: ZeroingString,
|
||||
) -> Result<ZeroingString, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path(data_dir_name.display().to_string());
|
||||
let wallet_seed = WalletSeed::from_file(&data_dir_name, password)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
let res = wallet_seed
|
||||
.to_mnemonic()
|
||||
.map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?;
|
||||
Ok(ZeroingString::from(res))
|
||||
}
|
||||
|
||||
fn validate_mnemonic(&self, mnemonic: ZeroingString) -> Result<(), Error> {
|
||||
match WalletSeed::from_mnemonic(mnemonic) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(Error::GenericError("Validating mnemonic".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn recover_from_mnemonic(
|
||||
&self,
|
||||
mnemonic: ZeroingString,
|
||||
password: ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
WalletSeed::recover_from_phrase(data_dir_name, mnemonic, password)
|
||||
.map_err(|_| Error::Lifecycle("Error recovering from mnemonic".into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn change_password(
|
||||
&self,
|
||||
_name: Option<&str>,
|
||||
old: ZeroingString,
|
||||
new: ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
// get seed for later check
|
||||
|
||||
let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
let orig_mnemonic = orig_wallet_seed
|
||||
.to_mnemonic()
|
||||
.map_err(|_| Error::Lifecycle("Error recovering mnemonic".into()))?;
|
||||
|
||||
// Back up existing seed, and keep track of filename as we're deleting it
|
||||
// once the password change is confirmed
|
||||
let backup_name = WalletSeed::backup_seed(data_dir_name)
|
||||
.map_err(|_| Error::Lifecycle("Error temporarily backing up existing seed".into()))?;
|
||||
|
||||
// Delete seed file
|
||||
WalletSeed::delete_seed_file(data_dir_name).map_err(|_| {
|
||||
Error::Lifecycle("Unable to delete seed file for password change".into())
|
||||
})?;
|
||||
|
||||
// Init a new file
|
||||
let _ = WalletSeed::init_file(
|
||||
data_dir_name,
|
||||
0,
|
||||
Some(ZeroingString::from(orig_mnemonic)),
|
||||
new.clone(),
|
||||
false,
|
||||
);
|
||||
info!("Wallet seed file created");
|
||||
|
||||
let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
|
||||
if orig_wallet_seed != new_wallet_seed {
|
||||
let msg =
|
||||
"New and Old wallet seeds are not equal on password change, not removing backups."
|
||||
.to_string();
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
// Removin
|
||||
info!("Password change confirmed, removing old seed file.");
|
||||
fs::remove_file(backup_name).map_err(|e| Error::IO(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_wallet(&self, _name: Option<&str>) -> Result<(), Error> {
|
||||
let data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
warn!(
|
||||
"Removing all wallet data from: {}",
|
||||
data_dir_name.to_str().unwrap()
|
||||
);
|
||||
fs::remove_dir_all(data_dir_name).map_err(|e| Error::IO(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wallet_inst(&mut self) -> Result<&mut Box<dyn WalletBackend<'a, C, K> + 'a>, Error> {
|
||||
match self.backend.as_mut() {
|
||||
None => {
|
||||
let msg = "Wallet has not been opened".into();
|
||||
Err(Error::Lifecycle(msg))
|
||||
}
|
||||
Some(_) => Ok(&mut *self.backend.as_mut().unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
//! Default wallet lifecycle provider
|
||||
|
||||
use crate::config::{
|
||||
config, GlobalWalletConfig, GlobalWalletConfigMembers, TorConfig, WalletConfig, GRIN_WALLET_DIR,
|
||||
};
|
||||
use crate::core::global;
|
||||
use crate::keychain::Keychain;
|
||||
use crate::libwallet::{Error, NodeClient, WalletBackend, WalletInitStatus, WalletLCProvider};
|
||||
use crate::lifecycle::seed::WalletSeed;
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::ZeroingString;
|
||||
use crate::LMDBBackend;
|
||||
use grin_util::logger::LoggingConfig;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
|
||||
// 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);
|
||||
let path = path.replace("\\", &sep);
|
||||
path
|
||||
}
|
||||
|
||||
pub struct DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
data_dir: String,
|
||||
node_client: C,
|
||||
backend: Option<Box<dyn WalletBackend<'a, C, K> + 'a>>,
|
||||
}
|
||||
|
||||
impl<'a, C, K> DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
/// Create new provider
|
||||
pub fn new(node_client: C) -> Self {
|
||||
DefaultLCProvider {
|
||||
node_client,
|
||||
data_dir: "default".to_owned(),
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, C, K> WalletLCProvider<'a, C, K> for DefaultLCProvider<'a, C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
fn set_top_level_directory(&mut self, dir: &str) -> Result<(), Error> {
|
||||
self.data_dir = dir.to_owned();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_top_level_directory(&self) -> Result<String, Error> {
|
||||
let sep = &MAIN_SEPARATOR.to_string();
|
||||
let data_dir = self
|
||||
.data_dir
|
||||
.to_owned()
|
||||
.replace("/", &sep)
|
||||
.replace("\\", &sep);
|
||||
Ok(data_dir)
|
||||
}
|
||||
|
||||
fn create_config(
|
||||
&self,
|
||||
chain_type: &global::ChainTypes,
|
||||
file_name: &str,
|
||||
wallet_config: Option<WalletConfig>,
|
||||
logging_config: Option<LoggingConfig>,
|
||||
tor_config: Option<TorConfig>,
|
||||
) -> Result<(), Error> {
|
||||
let mut default_config = GlobalWalletConfig::for_chain(&chain_type);
|
||||
let config_file_version = match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().config_file_version,
|
||||
None => None,
|
||||
};
|
||||
let logging = match logging_config {
|
||||
Some(l) => Some(l),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().logging,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
// Check if config was provided, if not load default and set update to "true"
|
||||
let (wallet, update) = match wallet_config {
|
||||
Some(w) => (w, false),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => (m.clone().wallet, true),
|
||||
None => (WalletConfig::default(), true),
|
||||
},
|
||||
};
|
||||
let tor = match tor_config {
|
||||
Some(t) => Some(t),
|
||||
None => match default_config.members.as_ref() {
|
||||
Some(m) => m.clone().tor,
|
||||
None => Some(TorConfig::default()),
|
||||
},
|
||||
};
|
||||
default_config = GlobalWalletConfig {
|
||||
members: Some(GlobalWalletConfigMembers {
|
||||
config_file_version,
|
||||
wallet,
|
||||
tor,
|
||||
logging,
|
||||
}),
|
||||
..default_config
|
||||
};
|
||||
let mut config_file_name = PathBuf::from(self.data_dir.clone());
|
||||
config_file_name.push(file_name);
|
||||
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
|
||||
if config_file_name.exists() && data_dir_name.exists() {
|
||||
let msg = format!(
|
||||
"{} already exists in the target directory ({}). Please remove it first",
|
||||
file_name,
|
||||
config_file_name.to_str().unwrap()
|
||||
);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
|
||||
// If config exists but the datadir return ok
|
||||
if config_file_name.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
// default settings are updated if no config was provided, no support for top_dir/here
|
||||
let mut abs_path_node = std::env::current_dir()?;
|
||||
abs_path_node.push(self.data_dir.clone());
|
||||
let mut absolute_path_wallet = std::env::current_dir()?;
|
||||
absolute_path_wallet.push(self.data_dir.clone());
|
||||
|
||||
// if no config provided, update defaults
|
||||
if update == true {
|
||||
// create top level dir if it doesn't exist
|
||||
let dd = PathBuf::from(self.data_dir.clone());
|
||||
if !dd.exists() {
|
||||
// try create
|
||||
fs::create_dir_all(dd)?;
|
||||
default_config.update_paths(&abs_path_node, &absolute_path_wallet);
|
||||
}
|
||||
};
|
||||
let res =
|
||||
default_config.write_to_file(config_file_name.to_str().unwrap(), false, None, None);
|
||||
if let Err(e) = res {
|
||||
let msg = format!(
|
||||
"Error creating config file as ({}): {}",
|
||||
config_file_name.to_str().unwrap(),
|
||||
e
|
||||
);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
|
||||
info!(
|
||||
"File {} configured and created",
|
||||
config_file_name.to_str().unwrap(),
|
||||
);
|
||||
|
||||
let mut api_secret_path = PathBuf::from(self.data_dir.clone());
|
||||
api_secret_path.push(PathBuf::from(config::API_SECRET_FILE_NAME));
|
||||
if !api_secret_path.exists() {
|
||||
config::init_api_secret(&api_secret_path).unwrap();
|
||||
} else {
|
||||
config::check_api_secret(&api_secret_path).unwrap();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_wallet(
|
||||
&mut self,
|
||||
_name: Option<&str>,
|
||||
mnemonic: Option<ZeroingString>,
|
||||
mnemonic_length: usize,
|
||||
password: ZeroingString,
|
||||
test_mode: bool,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path((data_dir_name.to_str().unwrap()).to_string());
|
||||
let exists = WalletSeed::seed_file_exists(&data_dir_name);
|
||||
if !test_mode {
|
||||
if let Ok(true) = exists {
|
||||
let msg = format!("Wallet seed already exists at4565: {}", data_dir_name);
|
||||
return Err(Error::WalletSeedExists(msg));
|
||||
}
|
||||
}
|
||||
WalletSeed::init_file(
|
||||
&data_dir_name,
|
||||
mnemonic_length,
|
||||
mnemonic.clone(),
|
||||
password,
|
||||
test_mode,
|
||||
)
|
||||
.map_err(|_| {
|
||||
Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned())
|
||||
})?;
|
||||
info!("Wallet seed file created");
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
error!("{}", msg);
|
||||
return Err(Error::Lifecycle(msg).into());
|
||||
}
|
||||
Ok(d) => d,
|
||||
};
|
||||
// Save init status of this wallet, to determine whether it needs a full UTXO scan
|
||||
let mut batch = wallet.batch_no_mask()?;
|
||||
match mnemonic {
|
||||
Some(_) => batch.save_init_status(WalletInitStatus::InitNeedsScanning)?,
|
||||
None => batch.save_init_status(WalletInitStatus::InitNoScanning)?,
|
||||
};
|
||||
batch.commit()?;
|
||||
info!("Wallet database backend created at {}", data_dir_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_wallet(
|
||||
&mut self,
|
||||
_name: Option<&str>,
|
||||
password: ZeroingString,
|
||||
create_mask: bool,
|
||||
use_test_rng: bool,
|
||||
) -> Result<Option<SecretKey>, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path(data_dir_name.to_str().unwrap().to_string());
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
Ok(d) => d,
|
||||
};
|
||||
let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| {
|
||||
Error::Lifecycle("Error opening wallet (is password correct?)".to_owned())
|
||||
})?;
|
||||
let keychain = wallet_seed
|
||||
.derive_keychain(global::is_testnet())
|
||||
.map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?;
|
||||
|
||||
let mask = wallet.set_keychain(Box::new(keychain), create_mask, use_test_rng)?;
|
||||
self.backend = Some(Box::new(wallet));
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
fn close_wallet(&mut self, _name: Option<&str>) -> Result<(), Error> {
|
||||
if let Some(b) = self.backend.as_mut() {
|
||||
b.close()?
|
||||
}
|
||||
self.backend = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wallet_exists(&self, _name: Option<&str>) -> Result<bool, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
let res = WalletSeed::seed_file_exists(&data_dir_name)
|
||||
.map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn get_mnemonic(
|
||||
&self,
|
||||
_name: Option<&str>,
|
||||
password: ZeroingString,
|
||||
) -> Result<ZeroingString, Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path(data_dir_name.display().to_string());
|
||||
let wallet_seed = WalletSeed::from_file(&data_dir_name, password)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
let res = wallet_seed
|
||||
.to_mnemonic()
|
||||
.map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?;
|
||||
Ok(ZeroingString::from(res))
|
||||
}
|
||||
|
||||
fn validate_mnemonic(&self, mnemonic: ZeroingString) -> Result<(), Error> {
|
||||
match WalletSeed::from_mnemonic(mnemonic) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(Error::GenericError("Validating mnemonic".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn recover_from_mnemonic(
|
||||
&self,
|
||||
mnemonic: ZeroingString,
|
||||
password: ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
WalletSeed::recover_from_phrase(data_dir_name, mnemonic, password)
|
||||
.map_err(|_| Error::Lifecycle("Error recovering from mnemonic".into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn change_password(
|
||||
&self,
|
||||
_name: Option<&str>,
|
||||
old: ZeroingString,
|
||||
new: ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
// get seed for later check
|
||||
|
||||
let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
let orig_mnemonic = orig_wallet_seed
|
||||
.to_mnemonic()
|
||||
.map_err(|_| Error::Lifecycle("Error recovering mnemonic".into()))?;
|
||||
|
||||
// Back up existing seed, and keep track of filename as we're deleting it
|
||||
// once the password change is confirmed
|
||||
let backup_name = WalletSeed::backup_seed(data_dir_name)
|
||||
.map_err(|_| Error::Lifecycle("Error temporarily backing up existing seed".into()))?;
|
||||
|
||||
// Delete seed file
|
||||
WalletSeed::delete_seed_file(data_dir_name).map_err(|_| {
|
||||
Error::Lifecycle("Unable to delete seed file for password change".into())
|
||||
})?;
|
||||
|
||||
// Init a new file
|
||||
let _ = WalletSeed::init_file(
|
||||
data_dir_name,
|
||||
0,
|
||||
Some(ZeroingString::from(orig_mnemonic)),
|
||||
new.clone(),
|
||||
false,
|
||||
);
|
||||
info!("Wallet seed file created");
|
||||
|
||||
let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
|
||||
if orig_wallet_seed != new_wallet_seed {
|
||||
let msg =
|
||||
"New and Old wallet seeds are not equal on password change, not removing backups."
|
||||
.to_string();
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
// Removin
|
||||
info!("Password change confirmed, removing old seed file.");
|
||||
fs::remove_file(backup_name).map_err(|e| Error::IO(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_wallet(&self, _name: Option<&str>) -> Result<(), Error> {
|
||||
let data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
warn!(
|
||||
"Removing all wallet data from: {}",
|
||||
data_dir_name.to_str().unwrap()
|
||||
);
|
||||
fs::remove_dir_all(data_dir_name).map_err(|e| Error::IO(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wallet_inst(&mut self) -> Result<&mut Box<dyn WalletBackend<'a, C, K> + 'a>, Error> {
|
||||
match self.backend.as_mut() {
|
||||
None => {
|
||||
let msg = "Wallet has not been opened".into();
|
||||
Err(Error::Lifecycle(msg))
|
||||
}
|
||||
Some(_) => Ok(&mut *self.backend.as_mut().unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -1,18 +1,18 @@
|
||||
// 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 default;
|
||||
mod seed;
|
||||
|
||||
pub use self::default::DefaultLCProvider;
|
||||
// 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 default;
|
||||
mod seed;
|
||||
|
||||
pub use self::default::DefaultLCProvider;
|
||||
|
||||
+385
-385
@@ -1,385 +1,385 @@
|
||||
// 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::blake2;
|
||||
use core::num::NonZeroU32;
|
||||
use rand::{thread_rng, Rng};
|
||||
use serde_json;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
|
||||
use ring::aead;
|
||||
use ring::pbkdf2;
|
||||
|
||||
use crate::keychain::{mnemonic, Keychain};
|
||||
use crate::util::{self, ToHex};
|
||||
use crate::Error;
|
||||
|
||||
pub const SEED_FILE: &str = "wallet.seed";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WalletSeed(Vec<u8>);
|
||||
|
||||
impl WalletSeed {
|
||||
pub fn from_bytes(bytes: &[u8]) -> WalletSeed {
|
||||
WalletSeed(bytes.to_vec())
|
||||
}
|
||||
|
||||
pub fn from_mnemonic(word_list: util::ZeroingString) -> Result<WalletSeed, Error> {
|
||||
let res = mnemonic::to_entropy(&word_list);
|
||||
match res {
|
||||
Ok(s) => Ok(WalletSeed::from_bytes(&s)),
|
||||
Err(_) => Err(Error::Mnemonic.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _from_hex(hex: &str) -> Result<WalletSeed, Error> {
|
||||
let bytes = util::from_hex(&hex.to_string())
|
||||
.map_err(|_| Error::GenericError("Invalid hex".to_owned()))?;
|
||||
Ok(WalletSeed::from_bytes(&bytes))
|
||||
}
|
||||
|
||||
pub fn _to_hex(&self) -> String {
|
||||
self.0.to_vec().to_hex()
|
||||
}
|
||||
|
||||
// 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);
|
||||
let path = path.replace("\\", &sep);
|
||||
path
|
||||
}
|
||||
pub fn to_mnemonic(&self) -> Result<String, Error> {
|
||||
let result = mnemonic::from_entropy(&self.0);
|
||||
match result {
|
||||
Ok(r) => Ok(r),
|
||||
Err(_) => Err(Error::Mnemonic.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _derive_keychain_old(old_wallet_seed: [u8; 32], password: &str) -> Vec<u8> {
|
||||
let seed = blake2::blake2b::blake2b(64, password.as_bytes(), &old_wallet_seed);
|
||||
seed.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
pub fn derive_keychain<K: Keychain>(&self, is_testnet: bool) -> Result<K, Error> {
|
||||
let result = K::from_seed(&self.0, is_testnet)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn init_new(
|
||||
seed_length: usize,
|
||||
test_mode: bool,
|
||||
password: Option<util::ZeroingString>,
|
||||
) -> WalletSeed {
|
||||
let mut seed: Vec<u8> = vec![];
|
||||
let mut rng = thread_rng();
|
||||
if !test_mode {
|
||||
for _ in 0..seed_length {
|
||||
seed.push(rng.gen());
|
||||
}
|
||||
} else {
|
||||
// Hash password and use for test seed so we have a way of keeping test wallets unique
|
||||
// but predictable
|
||||
seed = blake2::blake2b::blake2b(32, b"", password.unwrap().as_bytes())
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
}
|
||||
WalletSeed(seed)
|
||||
}
|
||||
|
||||
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
debug!("Seed file path: {}", seed_file_path);
|
||||
if Path::new(seed_file_path).exists() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backup_seed(data_file_dir: &str) -> Result<String, Error> {
|
||||
let seed_file_name = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
|
||||
|
||||
let mut path = Path::new(seed_file_name).to_path_buf();
|
||||
path.pop();
|
||||
let mut backup_seed_file_name =
|
||||
format!("{}{}{}.bak", data_file_dir, MAIN_SEPARATOR, SEED_FILE);
|
||||
let mut i = 1;
|
||||
while Path::new(&backup_seed_file_name).exists() {
|
||||
backup_seed_file_name =
|
||||
format!("{}{}{}.bak.{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE, i);
|
||||
i += 1;
|
||||
}
|
||||
path.push(backup_seed_file_name.clone());
|
||||
if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() {
|
||||
return Err(Error::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)
|
||||
}
|
||||
|
||||
pub fn recover_from_phrase(
|
||||
data_file_dir: &str,
|
||||
word_list: util::ZeroingString,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
debug!("data file dir: {}", data_file_dir);
|
||||
if let Ok(true) = WalletSeed::seed_file_exists(data_file_dir) {
|
||||
debug!("seed file exists");
|
||||
WalletSeed::backup_seed(data_file_dir)?;
|
||||
}
|
||||
if !Path::new(&data_file_dir).exists() {
|
||||
return Err(Error::WalletDoesntExist(
|
||||
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)?;
|
||||
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
|
||||
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&enc_seed_json.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
warn!("Seed created from word list");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn init_file(
|
||||
data_file_dir: &str,
|
||||
seed_length: usize,
|
||||
recovery_phrase: Option<util::ZeroingString>,
|
||||
password: util::ZeroingString,
|
||||
test_mode: bool,
|
||||
) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
let data_file_dir = Self::fmt_path(data_file_dir.to_string());
|
||||
warn!("Generating wallet seed file at: {}", seed_file_path);
|
||||
let exists = WalletSeed::seed_file_exists(&data_file_dir)?;
|
||||
if exists && !test_mode {
|
||||
let msg = format!("Wallet seed already exists at: {}", data_file_dir);
|
||||
error!("{}", msg);
|
||||
return Err(Error::WalletSeedExists(msg));
|
||||
}
|
||||
|
||||
let seed = match recovery_phrase {
|
||||
Some(p) => WalletSeed::from_mnemonic(p)?,
|
||||
None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())),
|
||||
};
|
||||
|
||||
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
|
||||
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
|
||||
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&enc_seed_json.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(seed)
|
||||
}
|
||||
|
||||
pub fn from_file(
|
||||
data_file_dir: &str,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
|
||||
debug!("Using wallet seed file at: {}", seed_file_path);
|
||||
|
||||
if Path::new(seed_file_path).exists() {
|
||||
let mut file = File::open(seed_file_path).map_err(|_| Error::IO)?;
|
||||
let mut buffer = String::new();
|
||||
file.read_to_string(&mut buffer).map_err(|_| Error::IO)?;
|
||||
let enc_seed: EncryptedWalletSeed =
|
||||
serde_json::from_str(&buffer).map_err(|_| Error::Format)?;
|
||||
let wallet_seed = enc_seed.decrypt(&password)?;
|
||||
Ok(wallet_seed)
|
||||
} else {
|
||||
error!(
|
||||
"wallet seed file {} could not be opened (grin-wallet init). \
|
||||
Run \"grin-wallet init\" to initialize a new wallet.",
|
||||
seed_file_path
|
||||
);
|
||||
Err(Error::WalletSeedDoesntExist)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_seed_file(data_file_dir: &str) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
if Path::new(seed_file_path).exists() {
|
||||
debug!("Deleting wallet seed file at: {}", seed_file_path);
|
||||
fs::remove_file(seed_file_path).map_err(|_| Error::IO)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypted wallet seed, for storing on disk and decrypting
|
||||
/// with provided password
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct EncryptedWalletSeed {
|
||||
encrypted_seed: String,
|
||||
/// Salt, not so useful in single case but include anyhow for situations
|
||||
/// where someone wants to store many of these
|
||||
pub salt: String,
|
||||
/// Nonce
|
||||
pub nonce: String,
|
||||
}
|
||||
|
||||
impl EncryptedWalletSeed {
|
||||
/// Create a new encrypted seed from the given seed + password
|
||||
pub fn from_seed(
|
||||
seed: &WalletSeed,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<EncryptedWalletSeed, Error> {
|
||||
let salt: [u8; 8] = thread_rng().gen();
|
||||
let nonce: [u8; 12] = thread_rng().gen();
|
||||
let password = password.as_bytes();
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(
|
||||
ring::pbkdf2::PBKDF2_HMAC_SHA512,
|
||||
NonZeroU32::new(100).unwrap(),
|
||||
&salt,
|
||||
password,
|
||||
&mut key,
|
||||
);
|
||||
let content = seed.0.to_vec();
|
||||
let mut enc_bytes = content;
|
||||
/*let suffix_len = aead::CHACHA20_POLY1305.tag_len();
|
||||
for _ in 0..suffix_len {
|
||||
enc_bytes.push(0);
|
||||
}*/
|
||||
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
|
||||
let sealing_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
|
||||
let aad = aead::Aad::from(&[]);
|
||||
let res = sealing_key.seal_in_place_append_tag(
|
||||
aead::Nonce::assume_unique_for_key(nonce),
|
||||
aad,
|
||||
&mut enc_bytes,
|
||||
);
|
||||
if let Err(_) = res {
|
||||
return Err(Error::Encryption);
|
||||
}
|
||||
|
||||
Ok(EncryptedWalletSeed {
|
||||
encrypted_seed: enc_bytes.to_hex(),
|
||||
salt: salt.to_hex(),
|
||||
nonce: nonce.to_hex(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Decrypt seed
|
||||
pub fn decrypt(&self, password: &str) -> Result<WalletSeed, Error> {
|
||||
let mut encrypted_seed = match util::from_hex(&self.encrypted_seed.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let salt = match util::from_hex(&self.salt.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let nonce = match util::from_hex(&self.nonce.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let password = password.as_bytes();
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(
|
||||
ring::pbkdf2::PBKDF2_HMAC_SHA512,
|
||||
NonZeroU32::new(100).unwrap(),
|
||||
&salt,
|
||||
password,
|
||||
&mut key,
|
||||
);
|
||||
|
||||
let mut n = [0u8; 12];
|
||||
n.copy_from_slice(&nonce[0..12]);
|
||||
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
|
||||
let opening_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
|
||||
let aad = aead::Aad::from(&[]);
|
||||
let res = opening_key.open_in_place(
|
||||
aead::Nonce::assume_unique_for_key(n),
|
||||
aad,
|
||||
&mut encrypted_seed,
|
||||
);
|
||||
if let Err(_) = res {
|
||||
return Err(Error::Encryption);
|
||||
}
|
||||
for _ in 0..aead::AES_256_GCM.tag_len() {
|
||||
encrypted_seed.pop();
|
||||
}
|
||||
|
||||
Ok(WalletSeed::from_bytes(&encrypted_seed))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::util::ZeroingString;
|
||||
#[test]
|
||||
fn wallet_seed_encrypt() {
|
||||
let password = ZeroingString::from("passwoid");
|
||||
let wallet_seed = WalletSeed::init_new(32, false, None);
|
||||
let mut enc_wallet_seed =
|
||||
EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap();
|
||||
println!("EWS: {:?}", enc_wallet_seed);
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password).unwrap();
|
||||
assert_eq!(wallet_seed, decrypted_wallet_seed);
|
||||
|
||||
// Wrong password
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt("");
|
||||
assert!(decrypted_wallet_seed.is_err());
|
||||
|
||||
// Wrong nonce
|
||||
enc_wallet_seed.nonce = "wrongnonce".to_owned();
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password);
|
||||
assert!(decrypted_wallet_seed.is_err());
|
||||
}
|
||||
}
|
||||
// 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::blake2;
|
||||
use core::num::NonZeroU32;
|
||||
use rand::{thread_rng, Rng};
|
||||
use serde_json;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
|
||||
use ring::aead;
|
||||
use ring::pbkdf2;
|
||||
|
||||
use crate::keychain::{mnemonic, Keychain};
|
||||
use crate::util::{self, ToHex};
|
||||
use crate::Error;
|
||||
|
||||
pub const SEED_FILE: &str = "wallet.seed";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WalletSeed(Vec<u8>);
|
||||
|
||||
impl WalletSeed {
|
||||
pub fn from_bytes(bytes: &[u8]) -> WalletSeed {
|
||||
WalletSeed(bytes.to_vec())
|
||||
}
|
||||
|
||||
pub fn from_mnemonic(word_list: util::ZeroingString) -> Result<WalletSeed, Error> {
|
||||
let res = mnemonic::to_entropy(&word_list);
|
||||
match res {
|
||||
Ok(s) => Ok(WalletSeed::from_bytes(&s)),
|
||||
Err(_) => Err(Error::Mnemonic.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _from_hex(hex: &str) -> Result<WalletSeed, Error> {
|
||||
let bytes = util::from_hex(&hex.to_string())
|
||||
.map_err(|_| Error::GenericError("Invalid hex".to_owned()))?;
|
||||
Ok(WalletSeed::from_bytes(&bytes))
|
||||
}
|
||||
|
||||
pub fn _to_hex(&self) -> String {
|
||||
self.0.to_vec().to_hex()
|
||||
}
|
||||
|
||||
// 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);
|
||||
let path = path.replace("\\", &sep);
|
||||
path
|
||||
}
|
||||
pub fn to_mnemonic(&self) -> Result<String, Error> {
|
||||
let result = mnemonic::from_entropy(&self.0);
|
||||
match result {
|
||||
Ok(r) => Ok(r),
|
||||
Err(_) => Err(Error::Mnemonic.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn _derive_keychain_old(old_wallet_seed: [u8; 32], password: &str) -> Vec<u8> {
|
||||
let seed = blake2::blake2b::blake2b(64, password.as_bytes(), &old_wallet_seed);
|
||||
seed.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
pub fn derive_keychain<K: Keychain>(&self, is_testnet: bool) -> Result<K, Error> {
|
||||
let result = K::from_seed(&self.0, is_testnet)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn init_new(
|
||||
seed_length: usize,
|
||||
test_mode: bool,
|
||||
password: Option<util::ZeroingString>,
|
||||
) -> WalletSeed {
|
||||
let mut seed: Vec<u8> = vec![];
|
||||
let mut rng = thread_rng();
|
||||
if !test_mode {
|
||||
for _ in 0..seed_length {
|
||||
seed.push(rng.gen());
|
||||
}
|
||||
} else {
|
||||
// Hash password and use for test seed so we have a way of keeping test wallets unique
|
||||
// but predictable
|
||||
seed = blake2::blake2b::blake2b(32, b"", password.unwrap().as_bytes())
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
}
|
||||
WalletSeed(seed)
|
||||
}
|
||||
|
||||
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
debug!("Seed file path: {}", seed_file_path);
|
||||
if Path::new(seed_file_path).exists() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backup_seed(data_file_dir: &str) -> Result<String, Error> {
|
||||
let seed_file_name = &format!("{}{}{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE,);
|
||||
|
||||
let mut path = Path::new(seed_file_name).to_path_buf();
|
||||
path.pop();
|
||||
let mut backup_seed_file_name =
|
||||
format!("{}{}{}.bak", data_file_dir, MAIN_SEPARATOR, SEED_FILE);
|
||||
let mut i = 1;
|
||||
while Path::new(&backup_seed_file_name).exists() {
|
||||
backup_seed_file_name =
|
||||
format!("{}{}{}.bak.{}", data_file_dir, MAIN_SEPARATOR, SEED_FILE, i);
|
||||
i += 1;
|
||||
}
|
||||
path.push(backup_seed_file_name.clone());
|
||||
if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() {
|
||||
return Err(Error::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)
|
||||
}
|
||||
|
||||
pub fn recover_from_phrase(
|
||||
data_file_dir: &str,
|
||||
word_list: util::ZeroingString,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
debug!("data file dir: {}", data_file_dir);
|
||||
if let Ok(true) = WalletSeed::seed_file_exists(data_file_dir) {
|
||||
debug!("seed file exists");
|
||||
WalletSeed::backup_seed(data_file_dir)?;
|
||||
}
|
||||
if !Path::new(&data_file_dir).exists() {
|
||||
return Err(Error::WalletDoesntExist(
|
||||
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)?;
|
||||
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
|
||||
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&enc_seed_json.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
warn!("Seed created from word list");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn init_file(
|
||||
data_file_dir: &str,
|
||||
seed_length: usize,
|
||||
recovery_phrase: Option<util::ZeroingString>,
|
||||
password: util::ZeroingString,
|
||||
test_mode: bool,
|
||||
) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
let data_file_dir = Self::fmt_path(data_file_dir.to_string());
|
||||
warn!("Generating wallet seed file at: {}", seed_file_path);
|
||||
let exists = WalletSeed::seed_file_exists(&data_file_dir)?;
|
||||
if exists && !test_mode {
|
||||
let msg = format!("Wallet seed already exists at: {}", data_file_dir);
|
||||
error!("{}", msg);
|
||||
return Err(Error::WalletSeedExists(msg));
|
||||
}
|
||||
|
||||
let seed = match recovery_phrase {
|
||||
Some(p) => WalletSeed::from_mnemonic(p)?,
|
||||
None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())),
|
||||
};
|
||||
|
||||
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
|
||||
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?;
|
||||
let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&enc_seed_json.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(seed)
|
||||
}
|
||||
|
||||
pub fn from_file(
|
||||
data_file_dir: &str,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<WalletSeed, Error> {
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(data_file_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
|
||||
debug!("Using wallet seed file at: {}", seed_file_path);
|
||||
|
||||
if Path::new(seed_file_path).exists() {
|
||||
let mut file = File::open(seed_file_path).map_err(|_| Error::IO)?;
|
||||
let mut buffer = String::new();
|
||||
file.read_to_string(&mut buffer).map_err(|_| Error::IO)?;
|
||||
let enc_seed: EncryptedWalletSeed =
|
||||
serde_json::from_str(&buffer).map_err(|_| Error::Format)?;
|
||||
let wallet_seed = enc_seed.decrypt(&password)?;
|
||||
Ok(wallet_seed)
|
||||
} else {
|
||||
error!(
|
||||
"wallet seed file {} could not be opened (grin-wallet init). \
|
||||
Run \"grin-wallet init\" to initialize a new wallet.",
|
||||
seed_file_path
|
||||
);
|
||||
Err(Error::WalletSeedDoesntExist)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_seed_file(data_file_dir: &str) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
if Path::new(seed_file_path).exists() {
|
||||
debug!("Deleting wallet seed file at: {}", seed_file_path);
|
||||
fs::remove_file(seed_file_path).map_err(|_| Error::IO)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypted wallet seed, for storing on disk and decrypting
|
||||
/// with provided password
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct EncryptedWalletSeed {
|
||||
encrypted_seed: String,
|
||||
/// Salt, not so useful in single case but include anyhow for situations
|
||||
/// where someone wants to store many of these
|
||||
pub salt: String,
|
||||
/// Nonce
|
||||
pub nonce: String,
|
||||
}
|
||||
|
||||
impl EncryptedWalletSeed {
|
||||
/// Create a new encrypted seed from the given seed + password
|
||||
pub fn from_seed(
|
||||
seed: &WalletSeed,
|
||||
password: util::ZeroingString,
|
||||
) -> Result<EncryptedWalletSeed, Error> {
|
||||
let salt: [u8; 8] = thread_rng().gen();
|
||||
let nonce: [u8; 12] = thread_rng().gen();
|
||||
let password = password.as_bytes();
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(
|
||||
ring::pbkdf2::PBKDF2_HMAC_SHA512,
|
||||
NonZeroU32::new(100).unwrap(),
|
||||
&salt,
|
||||
password,
|
||||
&mut key,
|
||||
);
|
||||
let content = seed.0.to_vec();
|
||||
let mut enc_bytes = content;
|
||||
/*let suffix_len = aead::CHACHA20_POLY1305.tag_len();
|
||||
for _ in 0..suffix_len {
|
||||
enc_bytes.push(0);
|
||||
}*/
|
||||
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
|
||||
let sealing_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
|
||||
let aad = aead::Aad::from(&[]);
|
||||
let res = sealing_key.seal_in_place_append_tag(
|
||||
aead::Nonce::assume_unique_for_key(nonce),
|
||||
aad,
|
||||
&mut enc_bytes,
|
||||
);
|
||||
if let Err(_) = res {
|
||||
return Err(Error::Encryption);
|
||||
}
|
||||
|
||||
Ok(EncryptedWalletSeed {
|
||||
encrypted_seed: enc_bytes.to_hex(),
|
||||
salt: salt.to_hex(),
|
||||
nonce: nonce.to_hex(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Decrypt seed
|
||||
pub fn decrypt(&self, password: &str) -> Result<WalletSeed, Error> {
|
||||
let mut encrypted_seed = match util::from_hex(&self.encrypted_seed.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let salt = match util::from_hex(&self.salt.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let nonce = match util::from_hex(&self.nonce.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Error::Encryption),
|
||||
};
|
||||
let password = password.as_bytes();
|
||||
let mut key = [0; 32];
|
||||
pbkdf2::derive(
|
||||
ring::pbkdf2::PBKDF2_HMAC_SHA512,
|
||||
NonZeroU32::new(100).unwrap(),
|
||||
&salt,
|
||||
password,
|
||||
&mut key,
|
||||
);
|
||||
|
||||
let mut n = [0u8; 12];
|
||||
n.copy_from_slice(&nonce[0..12]);
|
||||
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
|
||||
let opening_key: aead::LessSafeKey = aead::LessSafeKey::new(unbound_key);
|
||||
let aad = aead::Aad::from(&[]);
|
||||
let res = opening_key.open_in_place(
|
||||
aead::Nonce::assume_unique_for_key(n),
|
||||
aad,
|
||||
&mut encrypted_seed,
|
||||
);
|
||||
if let Err(_) = res {
|
||||
return Err(Error::Encryption);
|
||||
}
|
||||
for _ in 0..aead::AES_256_GCM.tag_len() {
|
||||
encrypted_seed.pop();
|
||||
}
|
||||
|
||||
Ok(WalletSeed::from_bytes(&encrypted_seed))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::util::ZeroingString;
|
||||
#[test]
|
||||
fn wallet_seed_encrypt() {
|
||||
let password = ZeroingString::from("passwoid");
|
||||
let wallet_seed = WalletSeed::init_new(32, false, None);
|
||||
let mut enc_wallet_seed =
|
||||
EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap();
|
||||
println!("EWS: {:?}", enc_wallet_seed);
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password).unwrap();
|
||||
assert_eq!(wallet_seed, decrypted_wallet_seed);
|
||||
|
||||
// Wrong password
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt("");
|
||||
assert!(decrypted_wallet_seed.is_err());
|
||||
|
||||
// Wrong nonce
|
||||
enc_wallet_seed.nonce = "wrongnonce".to_owned();
|
||||
let decrypted_wallet_seed = enc_wallet_seed.decrypt(&password);
|
||||
assert!(decrypted_wallet_seed.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+436
-436
@@ -1,436 +1,436 @@
|
||||
// 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.
|
||||
|
||||
//! Client functions, implementations of the NodeClient trait
|
||||
|
||||
use crate::api::{self, LocatedTxKernel, OutputListing, OutputPrintable};
|
||||
use crate::core::core::{Transaction, TxKernel};
|
||||
use crate::libwallet::{NodeClient, NodeVersionInfo};
|
||||
use futures::stream::FuturesUnordered;
|
||||
use futures::TryStreamExt;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
|
||||
use crate::client_utils::{Client, RUNTIME};
|
||||
use crate::libwallet;
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::ToHex;
|
||||
|
||||
use super::resp_types::*;
|
||||
use crate::client_utils::json_rpc::*;
|
||||
|
||||
const ENDPOINT: &str = "/v2/foreign";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HTTPNodeClient {
|
||||
client: Client,
|
||||
node_url: String,
|
||||
node_api_secret: Option<String>,
|
||||
node_version_info: Option<NodeVersionInfo>,
|
||||
}
|
||||
|
||||
impl HTTPNodeClient {
|
||||
/// Create a new client that will communicate with the given grin node
|
||||
pub fn new(
|
||||
node_url: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<HTTPNodeClient, libwallet::Error> {
|
||||
Ok(HTTPNodeClient {
|
||||
client: Client::new().map_err(|_| libwallet::Error::Node)?,
|
||||
node_url: node_url.to_owned(),
|
||||
node_api_secret: node_api_secret,
|
||||
node_version_info: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Allow returning the chain height without needing a wallet instantiated
|
||||
pub fn chain_height(&self) -> Result<(u64, String), libwallet::Error> {
|
||||
self.get_chain_tip()
|
||||
}
|
||||
|
||||
fn send_json_request<D: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
method: &str,
|
||||
params: &serde_json::Value,
|
||||
) -> Result<D, libwallet::Error> {
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let req = build_request(method, params);
|
||||
let res = self
|
||||
.client
|
||||
.post::<Request, Response>(url.as_str(), self.node_api_secret(), &req);
|
||||
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Error calling {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
Ok(inner) => match inner.clone().into_result() {
|
||||
Ok(r) => Ok(r),
|
||||
Err(e) => {
|
||||
error!("{:?}", inner);
|
||||
let report = format!("Unable to parse response for {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeClient for HTTPNodeClient {
|
||||
fn node_url(&self) -> &str {
|
||||
&self.node_url
|
||||
}
|
||||
fn node_api_secret(&self) -> Option<String> {
|
||||
self.node_api_secret.clone()
|
||||
}
|
||||
|
||||
fn set_node_url(&mut self, node_url: &str) {
|
||||
self.node_url = node_url.to_owned();
|
||||
}
|
||||
|
||||
fn set_node_api_secret(&mut self, node_api_secret: Option<String>) {
|
||||
self.node_api_secret = node_api_secret;
|
||||
}
|
||||
|
||||
fn get_version_info(&mut self) -> Option<NodeVersionInfo> {
|
||||
if let Some(v) = self.node_version_info.as_ref() {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let retval = match self
|
||||
.send_json_request::<GetVersionResp>("get_version", &serde_json::Value::Null)
|
||||
{
|
||||
Ok(n) => NodeVersionInfo {
|
||||
node_version: n.node_version,
|
||||
block_header_version: n.block_header_version,
|
||||
verified: Some(true),
|
||||
},
|
||||
Err(e) => {
|
||||
// If node isn't available, allow offline functions
|
||||
// unfortunately have to parse string due to error structure
|
||||
let err_string = format!("{}", e);
|
||||
if err_string.contains("404") {
|
||||
return Some(NodeVersionInfo {
|
||||
node_version: "1.0.0".into(),
|
||||
block_header_version: 1,
|
||||
verified: Some(false),
|
||||
});
|
||||
} else {
|
||||
error!("Unable to contact Node to get version info: {}, check your node is running", e);
|
||||
warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
self.node_version_info = Some(retval.clone());
|
||||
Some(retval)
|
||||
}
|
||||
|
||||
/// Posts a transaction to a grin node
|
||||
fn post_tx(&self, tx: &Transaction, fluff: bool) -> Result<(), libwallet::Error> {
|
||||
let params = json!([tx, fluff]);
|
||||
self.send_json_request::<serde_json::Value>("push_transaction", ¶ms)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the chain tip from a given node
|
||||
fn get_chain_tip(&self) -> Result<(u64, String), libwallet::Error> {
|
||||
let result = self.send_json_request::<GetTipResp>("get_tip", &serde_json::Value::Null)?;
|
||||
Ok((result.height, result.last_block_pushed))
|
||||
}
|
||||
|
||||
/// Get kernel implementation
|
||||
fn get_kernel(
|
||||
&mut self,
|
||||
excess: &pedersen::Commitment,
|
||||
min_height: Option<u64>,
|
||||
max_height: Option<u64>,
|
||||
) -> Result<Option<(TxKernel, u64, u64)>, libwallet::Error> {
|
||||
let method = "get_kernel";
|
||||
let params = json!([excess.0.as_ref().to_hex(), min_height, max_height]);
|
||||
// have to handle this manually since the error needs to be parsed
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let req = build_request(method, ¶ms);
|
||||
let res = self
|
||||
.client
|
||||
.post::<Request, Response>(url.as_str(), self.node_api_secret(), &req);
|
||||
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Error calling {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
Ok(inner) => match inner.clone().into_result::<LocatedTxKernel>() {
|
||||
Ok(r) => Ok(Some((r.tx_kernel, r.height, r.mmr_index))),
|
||||
Err(e) => {
|
||||
let contents = format!("{:?}", inner);
|
||||
if contents.contains("NotFound") {
|
||||
Ok(None)
|
||||
} else {
|
||||
let report = format!("Unable to parse response for {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve outputs from node
|
||||
fn get_outputs_from_node(
|
||||
&self,
|
||||
wallet_outputs: Vec<pedersen::Commitment>,
|
||||
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
|
||||
// build a map of api outputs by commit so we can look them up efficiently
|
||||
let mut api_outputs: HashMap<pedersen::Commitment, (String, u64, u64)> = HashMap::new();
|
||||
|
||||
if wallet_outputs.is_empty() {
|
||||
return Ok(api_outputs);
|
||||
}
|
||||
|
||||
// build vec of commits for inclusion in query
|
||||
let query_params: Vec<String> = wallet_outputs
|
||||
.iter()
|
||||
.map(|commit| format!("{}", commit.as_ref().to_hex()))
|
||||
.collect();
|
||||
|
||||
// going to leave this here even though we're moving
|
||||
// to the json RPC api to keep the functionality of
|
||||
// parallelizing larger requests. Will raise default
|
||||
// from 200 to 500, however
|
||||
let chunk_default = 500;
|
||||
let chunk_size = match env::var("GRIN_OUTPUT_QUERY_SIZE") {
|
||||
Ok(s) => match s.parse::<usize>() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Unable to parse GRIN_OUTPUT_QUERY_SIZE, defaulting to {}",
|
||||
chunk_default
|
||||
);
|
||||
error!("Reason: {}", e);
|
||||
chunk_default
|
||||
}
|
||||
},
|
||||
Err(_) => chunk_default,
|
||||
};
|
||||
|
||||
trace!("Output query chunk size is: {}", chunk_size);
|
||||
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let api_secret = self.node_api_secret();
|
||||
let cl = self.client.clone();
|
||||
let task = async move {
|
||||
let params: Vec<_> = query_params
|
||||
.chunks(chunk_size)
|
||||
.map(|c| json!([c, null, null, false, false]))
|
||||
.collect();
|
||||
|
||||
let mut reqs = Vec::with_capacity(params.len());
|
||||
for p in ¶ms {
|
||||
reqs.push(build_request("get_outputs", p));
|
||||
}
|
||||
|
||||
let mut tasks = Vec::with_capacity(params.len());
|
||||
for req in &reqs {
|
||||
tasks.push(cl.post_async::<Request, Response>(
|
||||
url.as_str(),
|
||||
req,
|
||||
api_secret.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
let task: FuturesUnordered<_> = tasks.into_iter().collect();
|
||||
task.try_collect().await
|
||||
};
|
||||
|
||||
let rt = RUNTIME.clone();
|
||||
let res: Result<Vec<_>, _> =
|
||||
std::thread::spawn(move || rt.lock().unwrap().block_on(async move { task.await }))
|
||||
.join()
|
||||
.unwrap();
|
||||
|
||||
let results: Vec<OutputPrintable> = match res {
|
||||
Ok(resps) => {
|
||||
let mut results = vec![];
|
||||
for r in resps {
|
||||
match r.into_result::<Vec<OutputPrintable>>() {
|
||||
Ok(mut r) => results.append(&mut r),
|
||||
Err(e) => {
|
||||
let report = format!("Unable to parse response for get_outputs: {}", e);
|
||||
error!("{}", report);
|
||||
return Err(libwallet::Error::ClientCallback(report));
|
||||
}
|
||||
};
|
||||
}
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
let report = format!("Getting outputs by id: {}", e);
|
||||
error!("Outputs by id failed: {}", e);
|
||||
return Err(libwallet::Error::ClientCallback(report));
|
||||
}
|
||||
};
|
||||
|
||||
for out in results.iter() {
|
||||
let height = match out.block_height {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let msg = format!("Missing block height for output {:?}", out.commit);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
api_outputs.insert(
|
||||
out.commit,
|
||||
(out.commit.as_ref().to_hex(), height, out.mmr_index),
|
||||
);
|
||||
}
|
||||
Ok(api_outputs)
|
||||
}
|
||||
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&self,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
max_outputs: u64,
|
||||
) -> Result<
|
||||
(
|
||||
u64,
|
||||
u64,
|
||||
Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
|
||||
),
|
||||
libwallet::Error,
|
||||
> {
|
||||
let mut api_outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)> =
|
||||
Vec::new();
|
||||
|
||||
let params = json!([start_index, end_index, max_outputs, Some(true)]);
|
||||
let res = self.send_json_request::<OutputListing>("get_unspent_outputs", ¶ms)?;
|
||||
// We asked for unspent outputs via the api but defensively filter out spent outputs just in case.
|
||||
for out in res.outputs.into_iter().filter(|out| out.spent == false) {
|
||||
let is_coinbase = match out.output_type {
|
||||
api::OutputType::Coinbase => true,
|
||||
api::OutputType::Transaction => false,
|
||||
};
|
||||
let range_proof = match out.range_proof() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let msg = format!(
|
||||
"Unexpected error in returned output (missing range proof): {:?}. {:?}, {}",
|
||||
out.commit, out, e
|
||||
);
|
||||
error!("{}", msg);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
let block_height = match out.block_height {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let msg = format!(
|
||||
"Unexpected error in returned output (missing block height): {:?}. {:?}",
|
||||
out.commit, out
|
||||
);
|
||||
error!("{}", msg);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
api_outputs.push((
|
||||
out.commit,
|
||||
range_proof,
|
||||
is_coinbase,
|
||||
block_height,
|
||||
out.mmr_index,
|
||||
));
|
||||
}
|
||||
Ok((res.highest_index, res.last_retrieved_index, api_outputs))
|
||||
}
|
||||
|
||||
fn height_range_to_pmmr_indices(
|
||||
&self,
|
||||
start_height: u64,
|
||||
end_height: Option<u64>,
|
||||
) -> Result<(u64, u64), libwallet::Error> {
|
||||
let params = json!([start_height, end_height]);
|
||||
let res = self.send_json_request::<OutputListing>("get_pmmr_indices", ¶ms)?;
|
||||
|
||||
Ok((res.last_retrieved_index, res.highest_index))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::core::core::{KernelFeatures, OutputFeatures, OutputIdentifier};
|
||||
use crate::core::libtx::build;
|
||||
use crate::core::libtx::ProofBuilder;
|
||||
use crate::keychain::{ExtKeychain, Keychain};
|
||||
|
||||
// JSON api for "push_transaction" between wallet->node currently only supports "feature and commit" inputs.
|
||||
// We will need to revisit this if we decide to support "commit only" inputs (no features) at wallet level.
|
||||
fn tx1i1o_v2_compatible() -> Transaction {
|
||||
let keychain = ExtKeychain::from_random_seed(false).unwrap();
|
||||
let builder = ProofBuilder::new(&keychain);
|
||||
let key_id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
|
||||
let key_id2 = ExtKeychain::derive_key_id(1, 2, 0, 0, 0);
|
||||
let tx = build::transaction(
|
||||
KernelFeatures::Plain { fee: 2.into() },
|
||||
&[build::input(5, key_id1), build::output(3, key_id2)],
|
||||
&keychain,
|
||||
&builder,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let inputs: Vec<_> = tx.inputs().into();
|
||||
let inputs: Vec<_> = inputs
|
||||
.iter()
|
||||
.map(|input| OutputIdentifier {
|
||||
features: OutputFeatures::Plain,
|
||||
commit: input.commitment(),
|
||||
})
|
||||
.collect();
|
||||
Transaction {
|
||||
body: tx.body.replace_inputs(inputs.as_slice().into()),
|
||||
..tx
|
||||
}
|
||||
}
|
||||
|
||||
// Wallet will "push" a transaction to node, serializing the transaction as json.
|
||||
// We are testing the json structure is what we expect here.
|
||||
#[test]
|
||||
fn test_transaction_json_ser_deser() {
|
||||
let tx1 = tx1i1o_v2_compatible();
|
||||
let value = serde_json::to_value(&tx1).unwrap();
|
||||
|
||||
assert!(value["offset"].is_string());
|
||||
assert_eq!(value["body"]["inputs"][0]["features"], "Plain");
|
||||
assert!(value["body"]["inputs"][0]["commit"].is_string());
|
||||
assert_eq!(value["body"]["outputs"][0]["features"], "Plain");
|
||||
assert!(value["body"]["outputs"][0]["commit"].is_string());
|
||||
assert!(value["body"]["outputs"][0]["proof"].is_string());
|
||||
|
||||
// Note: Tx kernel "features" serialize in a slightly unexpected way.
|
||||
assert_eq!(value["body"]["kernels"][0]["features"]["Plain"]["fee"], 2);
|
||||
assert!(value["body"]["kernels"][0]["excess"].is_string());
|
||||
assert!(value["body"]["kernels"][0]["excess_sig"].is_string());
|
||||
|
||||
let tx2: Transaction = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(tx1, tx2);
|
||||
|
||||
let str = serde_json::to_string(&tx1).unwrap();
|
||||
println!("{}", str);
|
||||
let tx2: Transaction = serde_json::from_str(&str).unwrap();
|
||||
assert_eq!(tx1, tx2);
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
//! Client functions, implementations of the NodeClient trait
|
||||
|
||||
use crate::api::{self, LocatedTxKernel, OutputListing, OutputPrintable};
|
||||
use crate::core::core::{Transaction, TxKernel};
|
||||
use crate::libwallet::{NodeClient, NodeVersionInfo};
|
||||
use futures::stream::FuturesUnordered;
|
||||
use futures::TryStreamExt;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
|
||||
use crate::client_utils::{Client, RUNTIME};
|
||||
use crate::libwallet;
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::ToHex;
|
||||
|
||||
use super::resp_types::*;
|
||||
use crate::client_utils::json_rpc::*;
|
||||
|
||||
const ENDPOINT: &str = "/v2/foreign";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HTTPNodeClient {
|
||||
client: Client,
|
||||
node_url: String,
|
||||
node_api_secret: Option<String>,
|
||||
node_version_info: Option<NodeVersionInfo>,
|
||||
}
|
||||
|
||||
impl HTTPNodeClient {
|
||||
/// Create a new client that will communicate with the given grin node
|
||||
pub fn new(
|
||||
node_url: &str,
|
||||
node_api_secret: Option<String>,
|
||||
) -> Result<HTTPNodeClient, libwallet::Error> {
|
||||
Ok(HTTPNodeClient {
|
||||
client: Client::new().map_err(|_| libwallet::Error::Node)?,
|
||||
node_url: node_url.to_owned(),
|
||||
node_api_secret: node_api_secret,
|
||||
node_version_info: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Allow returning the chain height without needing a wallet instantiated
|
||||
pub fn chain_height(&self) -> Result<(u64, String), libwallet::Error> {
|
||||
self.get_chain_tip()
|
||||
}
|
||||
|
||||
fn send_json_request<D: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
method: &str,
|
||||
params: &serde_json::Value,
|
||||
) -> Result<D, libwallet::Error> {
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let req = build_request(method, params);
|
||||
let res = self
|
||||
.client
|
||||
.post::<Request, Response>(url.as_str(), self.node_api_secret(), &req);
|
||||
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Error calling {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
Ok(inner) => match inner.clone().into_result() {
|
||||
Ok(r) => Ok(r),
|
||||
Err(e) => {
|
||||
error!("{:?}", inner);
|
||||
let report = format!("Unable to parse response for {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeClient for HTTPNodeClient {
|
||||
fn node_url(&self) -> &str {
|
||||
&self.node_url
|
||||
}
|
||||
fn node_api_secret(&self) -> Option<String> {
|
||||
self.node_api_secret.clone()
|
||||
}
|
||||
|
||||
fn set_node_url(&mut self, node_url: &str) {
|
||||
self.node_url = node_url.to_owned();
|
||||
}
|
||||
|
||||
fn set_node_api_secret(&mut self, node_api_secret: Option<String>) {
|
||||
self.node_api_secret = node_api_secret;
|
||||
}
|
||||
|
||||
fn get_version_info(&mut self) -> Option<NodeVersionInfo> {
|
||||
if let Some(v) = self.node_version_info.as_ref() {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let retval = match self
|
||||
.send_json_request::<GetVersionResp>("get_version", &serde_json::Value::Null)
|
||||
{
|
||||
Ok(n) => NodeVersionInfo {
|
||||
node_version: n.node_version,
|
||||
block_header_version: n.block_header_version,
|
||||
verified: Some(true),
|
||||
},
|
||||
Err(e) => {
|
||||
// If node isn't available, allow offline functions
|
||||
// unfortunately have to parse string due to error structure
|
||||
let err_string = format!("{}", e);
|
||||
if err_string.contains("404") {
|
||||
return Some(NodeVersionInfo {
|
||||
node_version: "1.0.0".into(),
|
||||
block_header_version: 1,
|
||||
verified: Some(false),
|
||||
});
|
||||
} else {
|
||||
error!("Unable to contact Node to get version info: {}, check your node is running", e);
|
||||
warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
self.node_version_info = Some(retval.clone());
|
||||
Some(retval)
|
||||
}
|
||||
|
||||
/// Posts a transaction to a grin node
|
||||
fn post_tx(&self, tx: &Transaction, fluff: bool) -> Result<(), libwallet::Error> {
|
||||
let params = json!([tx, fluff]);
|
||||
self.send_json_request::<serde_json::Value>("push_transaction", ¶ms)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the chain tip from a given node
|
||||
fn get_chain_tip(&self) -> Result<(u64, String), libwallet::Error> {
|
||||
let result = self.send_json_request::<GetTipResp>("get_tip", &serde_json::Value::Null)?;
|
||||
Ok((result.height, result.last_block_pushed))
|
||||
}
|
||||
|
||||
/// Get kernel implementation
|
||||
fn get_kernel(
|
||||
&mut self,
|
||||
excess: &pedersen::Commitment,
|
||||
min_height: Option<u64>,
|
||||
max_height: Option<u64>,
|
||||
) -> Result<Option<(TxKernel, u64, u64)>, libwallet::Error> {
|
||||
let method = "get_kernel";
|
||||
let params = json!([excess.0.as_ref().to_hex(), min_height, max_height]);
|
||||
// have to handle this manually since the error needs to be parsed
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let req = build_request(method, ¶ms);
|
||||
let res = self
|
||||
.client
|
||||
.post::<Request, Response>(url.as_str(), self.node_api_secret(), &req);
|
||||
|
||||
match res {
|
||||
Err(e) => {
|
||||
let report = format!("Error calling {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
Ok(inner) => match inner.clone().into_result::<LocatedTxKernel>() {
|
||||
Ok(r) => Ok(Some((r.tx_kernel, r.height, r.mmr_index))),
|
||||
Err(e) => {
|
||||
let contents = format!("{:?}", inner);
|
||||
if contents.contains("NotFound") {
|
||||
Ok(None)
|
||||
} else {
|
||||
let report = format!("Unable to parse response for {}: {}", method, e);
|
||||
error!("{}", report);
|
||||
Err(libwallet::Error::ClientCallback(report))
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve outputs from node
|
||||
fn get_outputs_from_node(
|
||||
&self,
|
||||
wallet_outputs: Vec<pedersen::Commitment>,
|
||||
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
|
||||
// build a map of api outputs by commit so we can look them up efficiently
|
||||
let mut api_outputs: HashMap<pedersen::Commitment, (String, u64, u64)> = HashMap::new();
|
||||
|
||||
if wallet_outputs.is_empty() {
|
||||
return Ok(api_outputs);
|
||||
}
|
||||
|
||||
// build vec of commits for inclusion in query
|
||||
let query_params: Vec<String> = wallet_outputs
|
||||
.iter()
|
||||
.map(|commit| format!("{}", commit.as_ref().to_hex()))
|
||||
.collect();
|
||||
|
||||
// going to leave this here even though we're moving
|
||||
// to the json RPC api to keep the functionality of
|
||||
// parallelizing larger requests. Will raise default
|
||||
// from 200 to 500, however
|
||||
let chunk_default = 500;
|
||||
let chunk_size = match env::var("GRIN_OUTPUT_QUERY_SIZE") {
|
||||
Ok(s) => match s.parse::<usize>() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Unable to parse GRIN_OUTPUT_QUERY_SIZE, defaulting to {}",
|
||||
chunk_default
|
||||
);
|
||||
error!("Reason: {}", e);
|
||||
chunk_default
|
||||
}
|
||||
},
|
||||
Err(_) => chunk_default,
|
||||
};
|
||||
|
||||
trace!("Output query chunk size is: {}", chunk_size);
|
||||
|
||||
let url = format!("{}{}", self.node_url(), ENDPOINT);
|
||||
let api_secret = self.node_api_secret();
|
||||
let cl = self.client.clone();
|
||||
let task = async move {
|
||||
let params: Vec<_> = query_params
|
||||
.chunks(chunk_size)
|
||||
.map(|c| json!([c, null, null, false, false]))
|
||||
.collect();
|
||||
|
||||
let mut reqs = Vec::with_capacity(params.len());
|
||||
for p in ¶ms {
|
||||
reqs.push(build_request("get_outputs", p));
|
||||
}
|
||||
|
||||
let mut tasks = Vec::with_capacity(params.len());
|
||||
for req in &reqs {
|
||||
tasks.push(cl.post_async::<Request, Response>(
|
||||
url.as_str(),
|
||||
req,
|
||||
api_secret.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
let task: FuturesUnordered<_> = tasks.into_iter().collect();
|
||||
task.try_collect().await
|
||||
};
|
||||
|
||||
let rt = RUNTIME.clone();
|
||||
let res: Result<Vec<_>, _> =
|
||||
std::thread::spawn(move || rt.lock().unwrap().block_on(async move { task.await }))
|
||||
.join()
|
||||
.unwrap();
|
||||
|
||||
let results: Vec<OutputPrintable> = match res {
|
||||
Ok(resps) => {
|
||||
let mut results = vec![];
|
||||
for r in resps {
|
||||
match r.into_result::<Vec<OutputPrintable>>() {
|
||||
Ok(mut r) => results.append(&mut r),
|
||||
Err(e) => {
|
||||
let report = format!("Unable to parse response for get_outputs: {}", e);
|
||||
error!("{}", report);
|
||||
return Err(libwallet::Error::ClientCallback(report));
|
||||
}
|
||||
};
|
||||
}
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
let report = format!("Getting outputs by id: {}", e);
|
||||
error!("Outputs by id failed: {}", e);
|
||||
return Err(libwallet::Error::ClientCallback(report));
|
||||
}
|
||||
};
|
||||
|
||||
for out in results.iter() {
|
||||
let height = match out.block_height {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let msg = format!("Missing block height for output {:?}", out.commit);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
api_outputs.insert(
|
||||
out.commit,
|
||||
(out.commit.as_ref().to_hex(), height, out.mmr_index),
|
||||
);
|
||||
}
|
||||
Ok(api_outputs)
|
||||
}
|
||||
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&self,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
max_outputs: u64,
|
||||
) -> Result<
|
||||
(
|
||||
u64,
|
||||
u64,
|
||||
Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
|
||||
),
|
||||
libwallet::Error,
|
||||
> {
|
||||
let mut api_outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)> =
|
||||
Vec::new();
|
||||
|
||||
let params = json!([start_index, end_index, max_outputs, Some(true)]);
|
||||
let res = self.send_json_request::<OutputListing>("get_unspent_outputs", ¶ms)?;
|
||||
// We asked for unspent outputs via the api but defensively filter out spent outputs just in case.
|
||||
for out in res.outputs.into_iter().filter(|out| out.spent == false) {
|
||||
let is_coinbase = match out.output_type {
|
||||
api::OutputType::Coinbase => true,
|
||||
api::OutputType::Transaction => false,
|
||||
};
|
||||
let range_proof = match out.range_proof() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let msg = format!(
|
||||
"Unexpected error in returned output (missing range proof): {:?}. {:?}, {}",
|
||||
out.commit, out, e
|
||||
);
|
||||
error!("{}", msg);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
let block_height = match out.block_height {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let msg = format!(
|
||||
"Unexpected error in returned output (missing block height): {:?}. {:?}",
|
||||
out.commit, out
|
||||
);
|
||||
error!("{}", msg);
|
||||
return Err(libwallet::Error::ClientCallback(msg));
|
||||
}
|
||||
};
|
||||
api_outputs.push((
|
||||
out.commit,
|
||||
range_proof,
|
||||
is_coinbase,
|
||||
block_height,
|
||||
out.mmr_index,
|
||||
));
|
||||
}
|
||||
Ok((res.highest_index, res.last_retrieved_index, api_outputs))
|
||||
}
|
||||
|
||||
fn height_range_to_pmmr_indices(
|
||||
&self,
|
||||
start_height: u64,
|
||||
end_height: Option<u64>,
|
||||
) -> Result<(u64, u64), libwallet::Error> {
|
||||
let params = json!([start_height, end_height]);
|
||||
let res = self.send_json_request::<OutputListing>("get_pmmr_indices", ¶ms)?;
|
||||
|
||||
Ok((res.last_retrieved_index, res.highest_index))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::core::core::{KernelFeatures, OutputFeatures, OutputIdentifier};
|
||||
use crate::core::libtx::build;
|
||||
use crate::core::libtx::ProofBuilder;
|
||||
use crate::keychain::{ExtKeychain, Keychain};
|
||||
|
||||
// JSON api for "push_transaction" between wallet->node currently only supports "feature and commit" inputs.
|
||||
// We will need to revisit this if we decide to support "commit only" inputs (no features) at wallet level.
|
||||
fn tx1i1o_v2_compatible() -> Transaction {
|
||||
let keychain = ExtKeychain::from_random_seed(false).unwrap();
|
||||
let builder = ProofBuilder::new(&keychain);
|
||||
let key_id1 = ExtKeychain::derive_key_id(1, 1, 0, 0, 0);
|
||||
let key_id2 = ExtKeychain::derive_key_id(1, 2, 0, 0, 0);
|
||||
let tx = build::transaction(
|
||||
KernelFeatures::Plain { fee: 2.into() },
|
||||
&[build::input(5, key_id1), build::output(3, key_id2)],
|
||||
&keychain,
|
||||
&builder,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let inputs: Vec<_> = tx.inputs().into();
|
||||
let inputs: Vec<_> = inputs
|
||||
.iter()
|
||||
.map(|input| OutputIdentifier {
|
||||
features: OutputFeatures::Plain,
|
||||
commit: input.commitment(),
|
||||
})
|
||||
.collect();
|
||||
Transaction {
|
||||
body: tx.body.replace_inputs(inputs.as_slice().into()),
|
||||
..tx
|
||||
}
|
||||
}
|
||||
|
||||
// Wallet will "push" a transaction to node, serializing the transaction as json.
|
||||
// We are testing the json structure is what we expect here.
|
||||
#[test]
|
||||
fn test_transaction_json_ser_deser() {
|
||||
let tx1 = tx1i1o_v2_compatible();
|
||||
let value = serde_json::to_value(&tx1).unwrap();
|
||||
|
||||
assert!(value["offset"].is_string());
|
||||
assert_eq!(value["body"]["inputs"][0]["features"], "Plain");
|
||||
assert!(value["body"]["inputs"][0]["commit"].is_string());
|
||||
assert_eq!(value["body"]["outputs"][0]["features"], "Plain");
|
||||
assert!(value["body"]["outputs"][0]["commit"].is_string());
|
||||
assert!(value["body"]["outputs"][0]["proof"].is_string());
|
||||
|
||||
// Note: Tx kernel "features" serialize in a slightly unexpected way.
|
||||
assert_eq!(value["body"]["kernels"][0]["features"]["Plain"]["fee"], 2);
|
||||
assert!(value["body"]["kernels"][0]["excess"].is_string());
|
||||
assert!(value["body"]["kernels"][0]["excess_sig"].is_string());
|
||||
|
||||
let tx2: Transaction = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(tx1, tx2);
|
||||
|
||||
let str = serde_json::to_string(&tx1).unwrap();
|
||||
println!("{}", str);
|
||||
let tx2: Transaction = serde_json::from_str(&str).unwrap();
|
||||
assert_eq!(tx1, tx2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
// 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 http;
|
||||
mod resp_types;
|
||||
|
||||
pub use self::http::HTTPNodeClient;
|
||||
// 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 http;
|
||||
mod resp_types;
|
||||
|
||||
pub use self::http::HTTPNodeClient;
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
// 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.
|
||||
// Derived from https://github.com/apoelstra/rust-jsonrpc
|
||||
|
||||
//! JSON RPC Types for V2 node client
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetTipResp {
|
||||
pub height: u64,
|
||||
pub last_block_pushed: String,
|
||||
pub prev_block_to_last: String,
|
||||
pub total_difficulty: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetVersionResp {
|
||||
pub node_version: String,
|
||||
pub block_header_version: u16,
|
||||
}
|
||||
// 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.
|
||||
// Derived from https://github.com/apoelstra/rust-jsonrpc
|
||||
|
||||
//! JSON RPC Types for V2 node client
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetTipResp {
|
||||
pub height: u64,
|
||||
pub last_block_pushed: String,
|
||||
pub prev_block_to_last: String,
|
||||
pub total_difficulty: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GetVersionResp {
|
||||
pub node_version: String,
|
||||
pub block_header_version: u16,
|
||||
}
|
||||
|
||||
+276
-276
@@ -1,276 +1,276 @@
|
||||
// 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::api;
|
||||
use crate::chain;
|
||||
use crate::chain::Chain;
|
||||
use crate::core;
|
||||
use crate::core::core::{Output, Transaction, TxKernel};
|
||||
use crate::core::{consensus, global, pow};
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use crate::libwallet::api_impl::{foreign, owner};
|
||||
use crate::libwallet::{
|
||||
BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletInst, WalletLCProvider,
|
||||
};
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::Mutex;
|
||||
use chrono::Duration;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
mod testclient;
|
||||
|
||||
pub use self::{testclient::LocalWalletClient, testclient::WalletProxy};
|
||||
|
||||
/// Get an output from the chain locally and present it back as an API output
|
||||
fn get_output_local(chain: &chain::Chain, commit: pedersen::Commitment) -> Option<api::Output> {
|
||||
if chain.get_unspent(commit).unwrap().is_some() {
|
||||
let block_height = chain.get_header_for_output(commit).unwrap().height;
|
||||
let output_pos = chain.get_output_pos(&commit).unwrap_or(0);
|
||||
Some(api::Output::new(&commit, block_height, output_pos))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a kernel from the chain locally
|
||||
fn get_kernel_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
excess: &pedersen::Commitment,
|
||||
min_height: Option<u64>,
|
||||
max_height: Option<u64>,
|
||||
) -> Option<api::LocatedTxKernel> {
|
||||
chain
|
||||
.get_kernel_height(&excess, min_height, max_height)
|
||||
.unwrap()
|
||||
.map(|(tx_kernel, height, mmr_index)| api::LocatedTxKernel {
|
||||
tx_kernel,
|
||||
height,
|
||||
mmr_index,
|
||||
})
|
||||
}
|
||||
|
||||
/// get output listing traversing pmmr from local
|
||||
fn get_outputs_by_pmmr_index_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
max: u64,
|
||||
) -> api::OutputListing {
|
||||
let outputs = chain
|
||||
.unspent_outputs_by_pmmr_index(start_index, max, end_index)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: outputs.0,
|
||||
highest_index: outputs.1,
|
||||
outputs: outputs
|
||||
.2
|
||||
.iter()
|
||||
.map(|x| api::OutputPrintable::from_output(x, &chain, None, true, false).unwrap())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// get output listing in a given block range
|
||||
fn height_range_to_pmmr_indices_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
) -> api::OutputListing {
|
||||
let indices = chain
|
||||
.block_height_range_to_pmmr_indices(start_index, end_index)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: indices.0,
|
||||
highest_index: indices.1,
|
||||
outputs: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn create_block_with_reward(
|
||||
chain: &Chain,
|
||||
prev: core::core::BlockHeader,
|
||||
txs: &[Transaction],
|
||||
reward_output: Output,
|
||||
reward_kernel: TxKernel,
|
||||
) -> core::core::Block {
|
||||
let next_header_info =
|
||||
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
|
||||
let mut b = core::core::Block::new(
|
||||
&prev,
|
||||
txs,
|
||||
next_header_info.clone().difficulty,
|
||||
(reward_output, reward_kernel),
|
||||
)
|
||||
.unwrap();
|
||||
b.header.timestamp = prev.timestamp + Duration::seconds(60);
|
||||
b.header.pow.secondary_scaling = next_header_info.secondary_scaling;
|
||||
chain.set_txhashset_roots(&mut b).unwrap();
|
||||
pow::pow_size(
|
||||
&mut b.header,
|
||||
next_header_info.difficulty,
|
||||
global::proofsize(),
|
||||
global::min_edge_bits(),
|
||||
)
|
||||
.unwrap();
|
||||
b
|
||||
}
|
||||
|
||||
/// Adds a block with a given reward to the chain and mines it
|
||||
pub fn add_block_with_reward(
|
||||
chain: &Chain,
|
||||
txs: &[Transaction],
|
||||
reward_output: Output,
|
||||
reward_kernel: TxKernel,
|
||||
) {
|
||||
let prev = chain.head_header().unwrap();
|
||||
let block = create_block_with_reward(chain, prev, txs, reward_output, reward_kernel);
|
||||
process_block(chain, block);
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block
|
||||
/// and return the block
|
||||
pub fn create_block_for_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
prev: core::core::BlockHeader,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<core::core::Block, libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
// build block fees
|
||||
let fee_amt = txs.iter().map(|tx| tx.fee()).sum();
|
||||
let block_fees = BlockFees {
|
||||
fees: fee_amt,
|
||||
key_id: None,
|
||||
height: prev.height + 1,
|
||||
};
|
||||
// build coinbase (via api) and add block
|
||||
let coinbase_tx = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
foreign::build_coinbase(&mut **w, keychain_mask, &block_fees, false)?
|
||||
};
|
||||
let block = create_block_with_reward(chain, prev, txs, coinbase_tx.output, coinbase_tx.kernel);
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block, mines
|
||||
/// the block and adds it to the chain, with option transactions included.
|
||||
/// Helpful for building up precise wallet balances for testing.
|
||||
pub fn award_block_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let prev = chain.head_header().unwrap();
|
||||
let block = create_block_for_wallet(chain, prev, txs, wallet, keychain_mask)?;
|
||||
process_block(chain, block);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn process_block(chain: &Chain, block: core::core::Block) {
|
||||
chain.process_block(block, chain::Options::MINE).unwrap();
|
||||
chain.validate(false).unwrap();
|
||||
}
|
||||
|
||||
/// Award a blocks to a wallet directly
|
||||
pub fn award_blocks_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
number: usize,
|
||||
pause_between: bool,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
for _ in 0..number {
|
||||
award_block_to_wallet(chain, &[], wallet.clone(), keychain_mask)?;
|
||||
if pause_between {
|
||||
thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// send an amount to a destination
|
||||
pub fn send_to_dest<'a, L, C, K>(
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
client: LocalWalletClient,
|
||||
dest: &str,
|
||||
amount: u64,
|
||||
test_mode: bool,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let slate = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
let args = InitTxArgs {
|
||||
src_acct_name: None,
|
||||
amount,
|
||||
minimum_confirmations: 2,
|
||||
max_outputs: 500,
|
||||
num_change_outputs: 1,
|
||||
selection_strategy_is_use_all: true,
|
||||
..Default::default()
|
||||
};
|
||||
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)?;
|
||||
owner::finalize_tx(&mut **w, keychain_mask, &slate)?
|
||||
};
|
||||
let client = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
w.w2n_client().clone()
|
||||
};
|
||||
owner::post_tx(&client, slate.tx_or_err()?, false)?; // mines a block
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get wallet info totals
|
||||
pub fn wallet_info<'a, L, C, K>(
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<WalletInfo, libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let (wallet_refreshed, wallet_info) =
|
||||
owner::retrieve_summary_info(wallet, keychain_mask, &None, true, 1)?;
|
||||
assert!(wallet_refreshed);
|
||||
Ok(wallet_info)
|
||||
}
|
||||
// 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::api;
|
||||
use crate::chain;
|
||||
use crate::chain::Chain;
|
||||
use crate::core;
|
||||
use crate::core::core::{Output, Transaction, TxKernel};
|
||||
use crate::core::{consensus, global, pow};
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use crate::libwallet::api_impl::{foreign, owner};
|
||||
use crate::libwallet::{
|
||||
BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletInst, WalletLCProvider,
|
||||
};
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::Mutex;
|
||||
use chrono::Duration;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
mod testclient;
|
||||
|
||||
pub use self::{testclient::LocalWalletClient, testclient::WalletProxy};
|
||||
|
||||
/// Get an output from the chain locally and present it back as an API output
|
||||
fn get_output_local(chain: &chain::Chain, commit: pedersen::Commitment) -> Option<api::Output> {
|
||||
if chain.get_unspent(commit).unwrap().is_some() {
|
||||
let block_height = chain.get_header_for_output(commit).unwrap().height;
|
||||
let output_pos = chain.get_output_pos(&commit).unwrap_or(0);
|
||||
Some(api::Output::new(&commit, block_height, output_pos))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a kernel from the chain locally
|
||||
fn get_kernel_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
excess: &pedersen::Commitment,
|
||||
min_height: Option<u64>,
|
||||
max_height: Option<u64>,
|
||||
) -> Option<api::LocatedTxKernel> {
|
||||
chain
|
||||
.get_kernel_height(&excess, min_height, max_height)
|
||||
.unwrap()
|
||||
.map(|(tx_kernel, height, mmr_index)| api::LocatedTxKernel {
|
||||
tx_kernel,
|
||||
height,
|
||||
mmr_index,
|
||||
})
|
||||
}
|
||||
|
||||
/// get output listing traversing pmmr from local
|
||||
fn get_outputs_by_pmmr_index_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
max: u64,
|
||||
) -> api::OutputListing {
|
||||
let outputs = chain
|
||||
.unspent_outputs_by_pmmr_index(start_index, max, end_index)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: outputs.0,
|
||||
highest_index: outputs.1,
|
||||
outputs: outputs
|
||||
.2
|
||||
.iter()
|
||||
.map(|x| api::OutputPrintable::from_output(x, &chain, None, true, false).unwrap())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// get output listing in a given block range
|
||||
fn height_range_to_pmmr_indices_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
) -> api::OutputListing {
|
||||
let indices = chain
|
||||
.block_height_range_to_pmmr_indices(start_index, end_index)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: indices.0,
|
||||
highest_index: indices.1,
|
||||
outputs: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn create_block_with_reward(
|
||||
chain: &Chain,
|
||||
prev: core::core::BlockHeader,
|
||||
txs: &[Transaction],
|
||||
reward_output: Output,
|
||||
reward_kernel: TxKernel,
|
||||
) -> core::core::Block {
|
||||
let next_header_info =
|
||||
consensus::next_difficulty(prev.height + 1, chain.difficulty_iter().unwrap());
|
||||
let mut b = core::core::Block::new(
|
||||
&prev,
|
||||
txs,
|
||||
next_header_info.clone().difficulty,
|
||||
(reward_output, reward_kernel),
|
||||
)
|
||||
.unwrap();
|
||||
b.header.timestamp = prev.timestamp + Duration::seconds(60);
|
||||
b.header.pow.secondary_scaling = next_header_info.secondary_scaling;
|
||||
chain.set_txhashset_roots(&mut b).unwrap();
|
||||
pow::pow_size(
|
||||
&mut b.header,
|
||||
next_header_info.difficulty,
|
||||
global::proofsize(),
|
||||
global::min_edge_bits(),
|
||||
)
|
||||
.unwrap();
|
||||
b
|
||||
}
|
||||
|
||||
/// Adds a block with a given reward to the chain and mines it
|
||||
pub fn add_block_with_reward(
|
||||
chain: &Chain,
|
||||
txs: &[Transaction],
|
||||
reward_output: Output,
|
||||
reward_kernel: TxKernel,
|
||||
) {
|
||||
let prev = chain.head_header().unwrap();
|
||||
let block = create_block_with_reward(chain, prev, txs, reward_output, reward_kernel);
|
||||
process_block(chain, block);
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block
|
||||
/// and return the block
|
||||
pub fn create_block_for_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
prev: core::core::BlockHeader,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<core::core::Block, libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
// build block fees
|
||||
let fee_amt = txs.iter().map(|tx| tx.fee()).sum();
|
||||
let block_fees = BlockFees {
|
||||
fees: fee_amt,
|
||||
key_id: None,
|
||||
height: prev.height + 1,
|
||||
};
|
||||
// build coinbase (via api) and add block
|
||||
let coinbase_tx = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
foreign::build_coinbase(&mut **w, keychain_mask, &block_fees, false)?
|
||||
};
|
||||
let block = create_block_with_reward(chain, prev, txs, coinbase_tx.output, coinbase_tx.kernel);
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block, mines
|
||||
/// the block and adds it to the chain, with option transactions included.
|
||||
/// Helpful for building up precise wallet balances for testing.
|
||||
pub fn award_block_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let prev = chain.head_header().unwrap();
|
||||
let block = create_block_for_wallet(chain, prev, txs, wallet, keychain_mask)?;
|
||||
process_block(chain, block);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn process_block(chain: &Chain, block: core::core::Block) {
|
||||
chain.process_block(block, chain::Options::MINE).unwrap();
|
||||
chain.validate(false).unwrap();
|
||||
}
|
||||
|
||||
/// Award a blocks to a wallet directly
|
||||
pub fn award_blocks_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
number: usize,
|
||||
pause_between: bool,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
for _ in 0..number {
|
||||
award_block_to_wallet(chain, &[], wallet.clone(), keychain_mask)?;
|
||||
if pause_between {
|
||||
thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// send an amount to a destination
|
||||
pub fn send_to_dest<'a, L, C, K>(
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
client: LocalWalletClient,
|
||||
dest: &str,
|
||||
amount: u64,
|
||||
test_mode: bool,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let slate = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
let args = InitTxArgs {
|
||||
src_acct_name: None,
|
||||
amount,
|
||||
minimum_confirmations: 2,
|
||||
max_outputs: 500,
|
||||
num_change_outputs: 1,
|
||||
selection_strategy_is_use_all: true,
|
||||
..Default::default()
|
||||
};
|
||||
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)?;
|
||||
owner::finalize_tx(&mut **w, keychain_mask, &slate)?
|
||||
};
|
||||
let client = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
w.w2n_client().clone()
|
||||
};
|
||||
owner::post_tx(&client, slate.tx_or_err()?, false)?; // mines a block
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get wallet info totals
|
||||
pub fn wallet_info<'a, L, C, K>(
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<WalletInfo, libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
{
|
||||
let (wallet_refreshed, wallet_info) =
|
||||
owner::retrieve_summary_info(wallet, keychain_mask, &None, true, 1)?;
|
||||
assert!(wallet_refreshed);
|
||||
Ok(wallet_info)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+660
-660
File diff suppressed because it is too large
Load Diff
+382
-382
@@ -1,382 +1,382 @@
|
||||
// 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.
|
||||
|
||||
//! Tor Configuration + Onion (Hidden) Service operations
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::Error;
|
||||
use grin_wallet_util::OnionV3Address;
|
||||
|
||||
use ed25519_dalek::ExpandedSecretKey;
|
||||
use ed25519_dalek::PublicKey as DalekPublicKey;
|
||||
use ed25519_dalek::SecretKey as DalekSecretKey;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, MAIN_SEPARATOR};
|
||||
use std::string::String;
|
||||
|
||||
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> {
|
||||
use std::os::unix::prelude::*;
|
||||
fs::set_permissions(file_path, fs::Permissions::from_mode(0o700)).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn set_permissions(_file_path: &str) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TorRcConfigItem {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl TorRcConfigItem {
|
||||
/// Create new
|
||||
pub fn new(name: &str, value: &str) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
value: value.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TorRcConfig {
|
||||
pub items: Vec<TorRcConfigItem>,
|
||||
}
|
||||
|
||||
impl TorRcConfig {
|
||||
/// Create new
|
||||
pub fn new() -> Self {
|
||||
Self { items: vec![] }
|
||||
}
|
||||
|
||||
/// add item
|
||||
pub fn add_item(&mut self, name: &str, value: &str) {
|
||||
self.items.push(TorRcConfigItem::new(name, value));
|
||||
}
|
||||
|
||||
/// write to file
|
||||
pub fn write_to_file(&self, file_path: &str) -> Result<(), Error> {
|
||||
let mut file = File::create(file_path).map_err(|_| Error::IO)?;
|
||||
for item in &self.items {
|
||||
file.write_all(item.name.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(b" ").map_err(|_| Error::IO)?;
|
||||
file.write_all(item.value.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(b"\n").map_err(|_| Error::IO)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_onion_service_sec_key_file(
|
||||
os_directory: &str,
|
||||
sec_key: &DalekSecretKey,
|
||||
) -> Result<(), Error> {
|
||||
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, SEC_KEY_FILE);
|
||||
let mut file = File::create(key_file_path).map_err(|_| Error::IO)?;
|
||||
// Tag is always 32 bytes, so pad with null zeroes
|
||||
file.write(b"== ed25519v1-secret: type0 ==\0\0\0")
|
||||
.map_err(|_| Error::IO)?;
|
||||
let expanded_skey: ExpandedSecretKey = ExpandedSecretKey::from(sec_key);
|
||||
file.write_all(&expanded_skey.to_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_service_pub_key_file(
|
||||
os_directory: &str,
|
||||
pub_key: &DalekPublicKey,
|
||||
) -> Result<(), Error> {
|
||||
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, PUB_KEY_FILE);
|
||||
let mut file = File::create(key_file_path).map_err(|_| Error::IO)?;
|
||||
// Tag is always 32 bytes, so pad with null zeroes
|
||||
file.write(b"== ed25519v1-public: type0 ==\0\0\0")
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(pub_key.as_bytes()).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_service_hostname_file(os_directory: &str, hostname: &str) -> Result<(), Error> {
|
||||
let file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, HOSTNAME_FILE);
|
||||
let mut file = File::create(file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&format!("{}.onion\n", hostname).as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_auth_clients_dir(os_directory: &str) -> Result<(), Error> {
|
||||
let auth_dir_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, AUTH_CLIENTS_DIR);
|
||||
fs::create_dir_all(auth_dir_path).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
/// output an onion service config for the secret key, and return the address
|
||||
pub fn output_onion_service_config(
|
||||
tor_config_directory: &str,
|
||||
sec_key: &SecretKey,
|
||||
) -> Result<OnionV3Address, Error> {
|
||||
let d_sec_key = DalekSecretKey::from_bytes(&sec_key.0)
|
||||
.map_err(|_| Error::ED25519Key("Unable to parse private key".into()))?;
|
||||
let address = OnionV3Address::from_private(&sec_key.0)?;
|
||||
let hs_dir_file_path = format!(
|
||||
"{}{}{}{}{}",
|
||||
tor_config_directory, MAIN_SEPARATOR, HIDDEN_SERVICES_DIR, MAIN_SEPARATOR, address
|
||||
);
|
||||
|
||||
// If file already exists, don't overwrite it, just return address
|
||||
if Path::new(&hs_dir_file_path).exists() {
|
||||
return Ok(address);
|
||||
}
|
||||
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(&hs_dir_file_path).map_err(|_| Error::IO)?;
|
||||
|
||||
create_onion_service_sec_key_file(&hs_dir_file_path, &d_sec_key)?;
|
||||
create_onion_service_pub_key_file(&hs_dir_file_path, &address.to_ed25519()?)?;
|
||||
create_onion_service_hostname_file(&hs_dir_file_path, &address.to_string())?;
|
||||
create_onion_auth_clients_dir(&hs_dir_file_path)?;
|
||||
|
||||
set_permissions(&hs_dir_file_path)?;
|
||||
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
/// output torrc file given a list of hidden service directories
|
||||
pub fn output_torrc(
|
||||
tor_config_directory: &str,
|
||||
wallet_listener_addr: &str,
|
||||
socks_port: &str,
|
||||
service_dirs: &[String],
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
let torrc_file_path = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TORRC_FILE);
|
||||
|
||||
let tor_data_dir = format!("./{}", TOR_DATA_DIR);
|
||||
|
||||
let mut props = TorRcConfig::new();
|
||||
props.add_item("SocksPort", socks_port);
|
||||
props.add_item("DataDirectory", &tor_data_dir);
|
||||
|
||||
for dir in service_dirs {
|
||||
let service_file_name = format!("./{}{}{}", HIDDEN_SERVICES_DIR, MAIN_SEPARATOR, dir);
|
||||
props.add_item("HiddenServiceDir", &service_file_name);
|
||||
props.add_item("HiddenServicePort", &format!("80 {}", wallet_listener_addr));
|
||||
}
|
||||
|
||||
if !hm_tor_bridge.is_empty() {
|
||||
props.add_item("UseBridges", "1");
|
||||
for (key, value) in hm_tor_bridge {
|
||||
props.add_item(&key, &value);
|
||||
}
|
||||
}
|
||||
|
||||
if !hm_tor_proxy.is_empty() {
|
||||
for (key, value) in hm_tor_proxy {
|
||||
props.add_item(&key, &value);
|
||||
}
|
||||
}
|
||||
|
||||
props.write_to_file(&torrc_file_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// output entire tor config for a list of secret keys
|
||||
pub fn output_tor_listener_config(
|
||||
tor_config_directory: &str,
|
||||
wallet_listener_addr: &str,
|
||||
listener_keys: &[SecretKey],
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
let tor_data_dir = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TOR_DATA_DIR);
|
||||
|
||||
// create data directory if it doesn't exist
|
||||
fs::create_dir_all(&tor_data_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let mut service_dirs = vec![];
|
||||
|
||||
for k in listener_keys {
|
||||
let service_dir = output_onion_service_config(tor_config_directory, &k)?;
|
||||
service_dirs.push(service_dir.to_string());
|
||||
}
|
||||
|
||||
// hidden service listener doesn't need a socks port
|
||||
output_torrc(
|
||||
tor_config_directory,
|
||||
wallet_listener_addr,
|
||||
"0",
|
||||
&service_dirs,
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// output tor config for a send
|
||||
pub fn output_tor_sender_config(
|
||||
tor_config_dir: &str,
|
||||
socks_listener_addr: &str,
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
// create data directory if it doesn't exist
|
||||
fs::create_dir_all(&tor_config_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
output_torrc(
|
||||
tor_config_dir,
|
||||
"",
|
||||
socks_listener_addr,
|
||||
&[],
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_tor_address(input: &str) -> Result<(), Error> {
|
||||
match OnionV3Address::try_from(input) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
let msg = format!("{:?}", e);
|
||||
Err(Error::NotOnion(msg).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn complete_tor_address(input: &str) -> Result<String, Error> {
|
||||
is_tor_address(input)?;
|
||||
let mut input = input.to_uppercase();
|
||||
if !input.starts_with("HTTP://") && !input.starts_with("HTTPS://") {
|
||||
input = format!("HTTP://{}", input);
|
||||
}
|
||||
if !input.ends_with(".ONION") {
|
||||
input = format!("{}.ONION", input);
|
||||
}
|
||||
Ok(input.to_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use rand::rngs::mock::StepRng;
|
||||
|
||||
use crate::util::{self, secp, static_secp_instance};
|
||||
|
||||
pub fn clean_output_dir(test_dir: &str) {
|
||||
let _ = remove_dir_all::remove_dir_all(test_dir);
|
||||
}
|
||||
|
||||
pub fn setup(test_dir: &str) {
|
||||
util::init_test_logger();
|
||||
clean_output_dir(test_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service_config() -> Result<(), Error> {
|
||||
let test_dir = "target/test_output/onion_service";
|
||||
setup(test_dir);
|
||||
let secp_inst = static_secp_instance();
|
||||
let secp = secp_inst.lock();
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_tor_config() -> Result<(), Error> {
|
||||
let test_dir = "./target/test_output/tor";
|
||||
setup(test_dir);
|
||||
let secp_inst = static_secp_instance();
|
||||
let secp = secp_inst.lock();
|
||||
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
|
||||
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
|
||||
let hm = HashMap::new();
|
||||
output_tor_listener_config(test_dir, "127.0.0.1:3415", &[sec_key], hm.clone(), hm)?;
|
||||
clean_output_dir(test_dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_tor_address() -> Result<(), Error> {
|
||||
assert!(is_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid").is_ok());
|
||||
assert!(is_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid").is_ok());
|
||||
assert!(is_tor_address("kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid").is_ok());
|
||||
assert!(is_tor_address(
|
||||
"http://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_ok());
|
||||
assert!(is_tor_address(
|
||||
"https://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_ok());
|
||||
assert!(
|
||||
is_tor_address("http://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid")
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
is_tor_address("kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion")
|
||||
.is_ok()
|
||||
);
|
||||
// address too short
|
||||
assert!(is_tor_address(
|
||||
"http://kcgiy5g6m76nzlz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_err());
|
||||
assert!(is_tor_address("kcgiy5g6m76nzlz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid").is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complete_tor_address() -> Result<(), Error> {
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid")
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid")
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion")
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyi")
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
//! Tor Configuration + Onion (Hidden) Service operations
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::Error;
|
||||
use grin_wallet_util::OnionV3Address;
|
||||
|
||||
use ed25519_dalek::ExpandedSecretKey;
|
||||
use ed25519_dalek::PublicKey as DalekPublicKey;
|
||||
use ed25519_dalek::SecretKey as DalekSecretKey;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, MAIN_SEPARATOR};
|
||||
use std::string::String;
|
||||
|
||||
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> {
|
||||
use std::os::unix::prelude::*;
|
||||
fs::set_permissions(file_path, fs::Permissions::from_mode(0o700)).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn set_permissions(_file_path: &str) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TorRcConfigItem {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl TorRcConfigItem {
|
||||
/// Create new
|
||||
pub fn new(name: &str, value: &str) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
value: value.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TorRcConfig {
|
||||
pub items: Vec<TorRcConfigItem>,
|
||||
}
|
||||
|
||||
impl TorRcConfig {
|
||||
/// Create new
|
||||
pub fn new() -> Self {
|
||||
Self { items: vec![] }
|
||||
}
|
||||
|
||||
/// add item
|
||||
pub fn add_item(&mut self, name: &str, value: &str) {
|
||||
self.items.push(TorRcConfigItem::new(name, value));
|
||||
}
|
||||
|
||||
/// write to file
|
||||
pub fn write_to_file(&self, file_path: &str) -> Result<(), Error> {
|
||||
let mut file = File::create(file_path).map_err(|_| Error::IO)?;
|
||||
for item in &self.items {
|
||||
file.write_all(item.name.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(b" ").map_err(|_| Error::IO)?;
|
||||
file.write_all(item.value.as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(b"\n").map_err(|_| Error::IO)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_onion_service_sec_key_file(
|
||||
os_directory: &str,
|
||||
sec_key: &DalekSecretKey,
|
||||
) -> Result<(), Error> {
|
||||
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, SEC_KEY_FILE);
|
||||
let mut file = File::create(key_file_path).map_err(|_| Error::IO)?;
|
||||
// Tag is always 32 bytes, so pad with null zeroes
|
||||
file.write(b"== ed25519v1-secret: type0 ==\0\0\0")
|
||||
.map_err(|_| Error::IO)?;
|
||||
let expanded_skey: ExpandedSecretKey = ExpandedSecretKey::from(sec_key);
|
||||
file.write_all(&expanded_skey.to_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_service_pub_key_file(
|
||||
os_directory: &str,
|
||||
pub_key: &DalekPublicKey,
|
||||
) -> Result<(), Error> {
|
||||
let key_file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, PUB_KEY_FILE);
|
||||
let mut file = File::create(key_file_path).map_err(|_| Error::IO)?;
|
||||
// Tag is always 32 bytes, so pad with null zeroes
|
||||
file.write(b"== ed25519v1-public: type0 ==\0\0\0")
|
||||
.map_err(|_| Error::IO)?;
|
||||
file.write_all(pub_key.as_bytes()).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_service_hostname_file(os_directory: &str, hostname: &str) -> Result<(), Error> {
|
||||
let file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, HOSTNAME_FILE);
|
||||
let mut file = File::create(file_path).map_err(|_| Error::IO)?;
|
||||
file.write_all(&format!("{}.onion\n", hostname).as_bytes())
|
||||
.map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_onion_auth_clients_dir(os_directory: &str) -> Result<(), Error> {
|
||||
let auth_dir_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, AUTH_CLIENTS_DIR);
|
||||
fs::create_dir_all(auth_dir_path).map_err(|_| Error::IO)?;
|
||||
Ok(())
|
||||
}
|
||||
/// output an onion service config for the secret key, and return the address
|
||||
pub fn output_onion_service_config(
|
||||
tor_config_directory: &str,
|
||||
sec_key: &SecretKey,
|
||||
) -> Result<OnionV3Address, Error> {
|
||||
let d_sec_key = DalekSecretKey::from_bytes(&sec_key.0)
|
||||
.map_err(|_| Error::ED25519Key("Unable to parse private key".into()))?;
|
||||
let address = OnionV3Address::from_private(&sec_key.0)?;
|
||||
let hs_dir_file_path = format!(
|
||||
"{}{}{}{}{}",
|
||||
tor_config_directory, MAIN_SEPARATOR, HIDDEN_SERVICES_DIR, MAIN_SEPARATOR, address
|
||||
);
|
||||
|
||||
// If file already exists, don't overwrite it, just return address
|
||||
if Path::new(&hs_dir_file_path).exists() {
|
||||
return Ok(address);
|
||||
}
|
||||
|
||||
// create directory if it doesn't exist
|
||||
fs::create_dir_all(&hs_dir_file_path).map_err(|_| Error::IO)?;
|
||||
|
||||
create_onion_service_sec_key_file(&hs_dir_file_path, &d_sec_key)?;
|
||||
create_onion_service_pub_key_file(&hs_dir_file_path, &address.to_ed25519()?)?;
|
||||
create_onion_service_hostname_file(&hs_dir_file_path, &address.to_string())?;
|
||||
create_onion_auth_clients_dir(&hs_dir_file_path)?;
|
||||
|
||||
set_permissions(&hs_dir_file_path)?;
|
||||
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
/// output torrc file given a list of hidden service directories
|
||||
pub fn output_torrc(
|
||||
tor_config_directory: &str,
|
||||
wallet_listener_addr: &str,
|
||||
socks_port: &str,
|
||||
service_dirs: &[String],
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
let torrc_file_path = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TORRC_FILE);
|
||||
|
||||
let tor_data_dir = format!("./{}", TOR_DATA_DIR);
|
||||
|
||||
let mut props = TorRcConfig::new();
|
||||
props.add_item("SocksPort", socks_port);
|
||||
props.add_item("DataDirectory", &tor_data_dir);
|
||||
|
||||
for dir in service_dirs {
|
||||
let service_file_name = format!("./{}{}{}", HIDDEN_SERVICES_DIR, MAIN_SEPARATOR, dir);
|
||||
props.add_item("HiddenServiceDir", &service_file_name);
|
||||
props.add_item("HiddenServicePort", &format!("80 {}", wallet_listener_addr));
|
||||
}
|
||||
|
||||
if !hm_tor_bridge.is_empty() {
|
||||
props.add_item("UseBridges", "1");
|
||||
for (key, value) in hm_tor_bridge {
|
||||
props.add_item(&key, &value);
|
||||
}
|
||||
}
|
||||
|
||||
if !hm_tor_proxy.is_empty() {
|
||||
for (key, value) in hm_tor_proxy {
|
||||
props.add_item(&key, &value);
|
||||
}
|
||||
}
|
||||
|
||||
props.write_to_file(&torrc_file_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// output entire tor config for a list of secret keys
|
||||
pub fn output_tor_listener_config(
|
||||
tor_config_directory: &str,
|
||||
wallet_listener_addr: &str,
|
||||
listener_keys: &[SecretKey],
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
let tor_data_dir = format!("{}{}{}", tor_config_directory, MAIN_SEPARATOR, TOR_DATA_DIR);
|
||||
|
||||
// create data directory if it doesn't exist
|
||||
fs::create_dir_all(&tor_data_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
let mut service_dirs = vec![];
|
||||
|
||||
for k in listener_keys {
|
||||
let service_dir = output_onion_service_config(tor_config_directory, &k)?;
|
||||
service_dirs.push(service_dir.to_string());
|
||||
}
|
||||
|
||||
// hidden service listener doesn't need a socks port
|
||||
output_torrc(
|
||||
tor_config_directory,
|
||||
wallet_listener_addr,
|
||||
"0",
|
||||
&service_dirs,
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// output tor config for a send
|
||||
pub fn output_tor_sender_config(
|
||||
tor_config_dir: &str,
|
||||
socks_listener_addr: &str,
|
||||
hm_tor_bridge: HashMap<String, String>,
|
||||
hm_tor_proxy: HashMap<String, String>,
|
||||
) -> Result<(), Error> {
|
||||
// create data directory if it doesn't exist
|
||||
fs::create_dir_all(&tor_config_dir).map_err(|_| Error::IO)?;
|
||||
|
||||
output_torrc(
|
||||
tor_config_dir,
|
||||
"",
|
||||
socks_listener_addr,
|
||||
&[],
|
||||
hm_tor_bridge,
|
||||
hm_tor_proxy,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_tor_address(input: &str) -> Result<(), Error> {
|
||||
match OnionV3Address::try_from(input) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
let msg = format!("{:?}", e);
|
||||
Err(Error::NotOnion(msg).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn complete_tor_address(input: &str) -> Result<String, Error> {
|
||||
is_tor_address(input)?;
|
||||
let mut input = input.to_uppercase();
|
||||
if !input.starts_with("HTTP://") && !input.starts_with("HTTPS://") {
|
||||
input = format!("HTTP://{}", input);
|
||||
}
|
||||
if !input.ends_with(".ONION") {
|
||||
input = format!("{}.ONION", input);
|
||||
}
|
||||
Ok(input.to_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use rand::rngs::mock::StepRng;
|
||||
|
||||
use crate::util::{self, secp, static_secp_instance};
|
||||
|
||||
pub fn clean_output_dir(test_dir: &str) {
|
||||
let _ = remove_dir_all::remove_dir_all(test_dir);
|
||||
}
|
||||
|
||||
pub fn setup(test_dir: &str) {
|
||||
util::init_test_logger();
|
||||
clean_output_dir(test_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service_config() -> Result<(), Error> {
|
||||
let test_dir = "target/test_output/onion_service";
|
||||
setup(test_dir);
|
||||
let secp_inst = static_secp_instance();
|
||||
let secp = secp_inst.lock();
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_tor_config() -> Result<(), Error> {
|
||||
let test_dir = "./target/test_output/tor";
|
||||
setup(test_dir);
|
||||
let secp_inst = static_secp_instance();
|
||||
let secp = secp_inst.lock();
|
||||
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
|
||||
let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng);
|
||||
let hm = HashMap::new();
|
||||
output_tor_listener_config(test_dir, "127.0.0.1:3415", &[sec_key], hm.clone(), hm)?;
|
||||
clean_output_dir(test_dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_tor_address() -> Result<(), Error> {
|
||||
assert!(is_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid").is_ok());
|
||||
assert!(is_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid").is_ok());
|
||||
assert!(is_tor_address("kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid").is_ok());
|
||||
assert!(is_tor_address(
|
||||
"http://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_ok());
|
||||
assert!(is_tor_address(
|
||||
"https://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_ok());
|
||||
assert!(
|
||||
is_tor_address("http://kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid")
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
is_tor_address("kcgiy5g6m76nzlzz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion")
|
||||
.is_ok()
|
||||
);
|
||||
// address too short
|
||||
assert!(is_tor_address(
|
||||
"http://kcgiy5g6m76nzlz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid.onion"
|
||||
)
|
||||
.is_err());
|
||||
assert!(is_tor_address("kcgiy5g6m76nzlz4vyqmgdv34f6yokdqwfhdhaafanpo5p4fceibyid").is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complete_tor_address() -> Result<(), Error> {
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid")
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid")
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
"http://2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion",
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyid.onion")
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
complete_tor_address("2a6at2obto3uvkpkitqp4wxcg6u36qf534eucbskqciturczzc5suyi")
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -1,18 +1,18 @@
|
||||
// Copyright 2018 The Grin Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod bridge;
|
||||
pub mod config;
|
||||
pub mod process;
|
||||
pub mod proxy;
|
||||
// Copyright 2018 The Grin Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
pub mod bridge;
|
||||
pub mod config;
|
||||
pub mod process;
|
||||
pub mod proxy;
|
||||
|
||||
+288
-288
@@ -1,288 +1,288 @@
|
||||
// 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.
|
||||
|
||||
// BSD 3-Clause License
|
||||
//
|
||||
// Copyright (c) 2016, Dhole
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * Neither the name of the copyright holder nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
//! Tor process control
|
||||
//! Derived from from from https://github.com/Dhole/rust-tor-controller.git
|
||||
|
||||
extern crate chrono;
|
||||
extern crate regex;
|
||||
extern crate timer;
|
||||
|
||||
use regex::Regex;
|
||||
use std::fs::{self, File};
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, MAIN_SEPARATOR};
|
||||
use std::process::{Child, ChildStdout, Command, Stdio};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::thread;
|
||||
use sysinfo::{Process, ProcessExt, System, SystemExt};
|
||||
|
||||
#[cfg(windows)]
|
||||
const TOR_EXE_NAME: &str = "tor.exe";
|
||||
#[cfg(not(windows))]
|
||||
const TOR_EXE_NAME: &str = "tor";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Process(String),
|
||||
IO(io::Error),
|
||||
PID(String),
|
||||
Tor(String, Vec<String>),
|
||||
InvalidLogLine,
|
||||
InvalidBootstrapLine(String),
|
||||
Regex(regex::Error),
|
||||
ProcessNotStarted,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
pub struct TorProcess {
|
||||
tor_cmd: String,
|
||||
args: Vec<String>,
|
||||
torrc_path: Option<String>,
|
||||
completion_percent: u8,
|
||||
timeout: u32,
|
||||
working_dir: Option<String>,
|
||||
pub stdout: Option<BufReader<ChildStdout>>,
|
||||
pub process: Option<Child>,
|
||||
sys: System,
|
||||
}
|
||||
|
||||
impl TorProcess {
|
||||
pub fn new() -> Self {
|
||||
TorProcess {
|
||||
tor_cmd: TOR_EXE_NAME.to_string(),
|
||||
args: vec![],
|
||||
torrc_path: None,
|
||||
completion_percent: 100 as u8,
|
||||
timeout: 0 as u32,
|
||||
working_dir: None,
|
||||
stdout: None,
|
||||
process: None,
|
||||
sys: System::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_process(&mut self, pid: i32) -> Option<&Process> {
|
||||
self.sys.refresh_all();
|
||||
self.sys.process((pid as usize).into())
|
||||
}
|
||||
|
||||
pub fn tor_cmd(&mut self, tor_cmd: &str) -> &mut Self {
|
||||
self.tor_cmd = tor_cmd.to_string();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn torrc_path(&mut self, torrc_path: &str) -> &mut Self {
|
||||
self.torrc_path = Some(torrc_path.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn arg(&mut self, arg: String) -> &mut Self {
|
||||
self.args.push(arg);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn args(&mut self, args: Vec<String>) -> &mut Self {
|
||||
for arg in args {
|
||||
self.arg(arg);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn completion_percent(&mut self, completion_percent: u8) -> &mut Self {
|
||||
self.completion_percent = completion_percent;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn timeout(&mut self, timeout: u32) -> &mut Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn working_dir(&mut self, dir: &str) -> &mut Self {
|
||||
self.working_dir = Some(dir.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
// The tor process will have its stdout piped, so if the stdout lines are not consumed they
|
||||
// will keep accumulating over time, increasing the consumed memory.
|
||||
pub fn launch(&mut self) -> Result<&mut Self, Error> {
|
||||
let mut tor = Command::new(&self.tor_cmd);
|
||||
|
||||
if let Some(ref d) = self.working_dir {
|
||||
tor.current_dir(&d);
|
||||
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(Error::IO)?;
|
||||
let pid = pid
|
||||
.parse::<i32>()
|
||||
.map_err(|err| Error::PID(format!("{:?}", err)))?;
|
||||
if let Some(p) = self.get_process(pid) {
|
||||
let _ = p.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ref torrc_path) = self.torrc_path {
|
||||
tor.args(&vec!["-f", torrc_path]);
|
||||
}
|
||||
let mut tor_process = tor
|
||||
.args(&self.args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|err| {
|
||||
let msg = format!("TOR executable (`{}`) not found. Please ensure TOR is installed and on the path: {:?}", TOR_EXE_NAME, err);
|
||||
Error::Process(msg)
|
||||
})?;
|
||||
|
||||
if let Some(ref d) = self.working_dir {
|
||||
// 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(Error::IO)?;
|
||||
file.write_all(format!("{}", tor_process.id()).as_bytes())
|
||||
.map_err(Error::IO)?;
|
||||
}
|
||||
|
||||
let stdout = BufReader::new(tor_process.stdout.take().unwrap());
|
||||
|
||||
self.process = Some(tor_process);
|
||||
let completion_percent = self.completion_percent;
|
||||
|
||||
let (stdout_tx, stdout_rx) = channel();
|
||||
let stdout_timeout_tx = stdout_tx.clone();
|
||||
|
||||
let timer = timer::Timer::new();
|
||||
let _guard =
|
||||
timer.schedule_with_delay(chrono::Duration::seconds(self.timeout as i64), move || {
|
||||
stdout_timeout_tx.send(Err(Error::Timeout)).unwrap_or(());
|
||||
});
|
||||
let stdout_thread = thread::spawn(move || {
|
||||
stdout_tx
|
||||
.send(Self::parse_tor_stdout(stdout, completion_percent))
|
||||
.unwrap_or(());
|
||||
});
|
||||
match stdout_rx.recv().unwrap() {
|
||||
Ok(stdout) => {
|
||||
stdout_thread.join().unwrap();
|
||||
self.stdout = Some(stdout);
|
||||
Ok(self)
|
||||
}
|
||||
Err(err) => {
|
||||
self.kill().unwrap_or(());
|
||||
stdout_thread.join().unwrap();
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_tor_stdout(
|
||||
mut stdout: BufReader<ChildStdout>,
|
||||
completion_perc: u8,
|
||||
) -> Result<BufReader<ChildStdout>, Error> {
|
||||
let re_bootstrap = Regex::new(r"^\[notice\] Bootstrapped (?P<perc>[0-9]+)%(.*): ")
|
||||
.map_err(Error::Regex)?;
|
||||
|
||||
let timestamp_len = "May 16 02:50:08.792".len();
|
||||
let mut warnings = Vec::new();
|
||||
let mut raw_line = String::new();
|
||||
|
||||
while stdout
|
||||
.read_line(&mut raw_line)
|
||||
.map_err(|err| Error::Process(format!("{}", err)))?
|
||||
> 0
|
||||
{
|
||||
{
|
||||
if raw_line.len() < timestamp_len + 1 {
|
||||
return Err(Error::InvalidLogLine);
|
||||
}
|
||||
let timestamp = &raw_line[..timestamp_len];
|
||||
let line = &raw_line[timestamp_len + 1..raw_line.len() - 1];
|
||||
debug!("{} {}", timestamp, line);
|
||||
match line.split(' ').nth(0) {
|
||||
Some("[notice]") => {
|
||||
if let Some("Bootstrapped") = line.split(' ').nth(1) {
|
||||
let perc = re_bootstrap
|
||||
.captures(line)
|
||||
.and_then(|c| c.name("perc"))
|
||||
.and_then(|pc| pc.as_str().parse::<u8>().ok())
|
||||
.ok_or_else(|| Error::InvalidBootstrapLine(line.to_string()))?;
|
||||
|
||||
if perc >= completion_perc {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("[warn]") => warnings.push(line.to_string()),
|
||||
Some("[err]") => return Err(Error::Tor(line.to_string(), warnings)),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
raw_line.clear();
|
||||
}
|
||||
Ok(stdout)
|
||||
}
|
||||
|
||||
pub fn kill(&mut self) -> Result<(), Error> {
|
||||
if let Some(ref mut process) = self.process {
|
||||
Ok(process
|
||||
.kill()
|
||||
.map_err(|err| Error::Process(format!("{}", err)))?)
|
||||
} else {
|
||||
Err(Error::ProcessNotStarted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TorProcess {
|
||||
// kill the child
|
||||
fn drop(&mut self) {
|
||||
debug!("Dropping TOR process");
|
||||
self.kill().unwrap_or(());
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
|
||||
// BSD 3-Clause License
|
||||
//
|
||||
// Copyright (c) 2016, Dhole
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * Neither the name of the copyright holder nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
//! Tor process control
|
||||
//! Derived from from from https://github.com/Dhole/rust-tor-controller.git
|
||||
|
||||
extern crate chrono;
|
||||
extern crate regex;
|
||||
extern crate timer;
|
||||
|
||||
use regex::Regex;
|
||||
use std::fs::{self, File};
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, MAIN_SEPARATOR};
|
||||
use std::process::{Child, ChildStdout, Command, Stdio};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::thread;
|
||||
use sysinfo::{Process, ProcessExt, System, SystemExt};
|
||||
|
||||
#[cfg(windows)]
|
||||
const TOR_EXE_NAME: &str = "tor.exe";
|
||||
#[cfg(not(windows))]
|
||||
const TOR_EXE_NAME: &str = "tor";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Process(String),
|
||||
IO(io::Error),
|
||||
PID(String),
|
||||
Tor(String, Vec<String>),
|
||||
InvalidLogLine,
|
||||
InvalidBootstrapLine(String),
|
||||
Regex(regex::Error),
|
||||
ProcessNotStarted,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
pub struct TorProcess {
|
||||
tor_cmd: String,
|
||||
args: Vec<String>,
|
||||
torrc_path: Option<String>,
|
||||
completion_percent: u8,
|
||||
timeout: u32,
|
||||
working_dir: Option<String>,
|
||||
pub stdout: Option<BufReader<ChildStdout>>,
|
||||
pub process: Option<Child>,
|
||||
sys: System,
|
||||
}
|
||||
|
||||
impl TorProcess {
|
||||
pub fn new() -> Self {
|
||||
TorProcess {
|
||||
tor_cmd: TOR_EXE_NAME.to_string(),
|
||||
args: vec![],
|
||||
torrc_path: None,
|
||||
completion_percent: 100 as u8,
|
||||
timeout: 0 as u32,
|
||||
working_dir: None,
|
||||
stdout: None,
|
||||
process: None,
|
||||
sys: System::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_process(&mut self, pid: i32) -> Option<&Process> {
|
||||
self.sys.refresh_all();
|
||||
self.sys.process((pid as usize).into())
|
||||
}
|
||||
|
||||
pub fn tor_cmd(&mut self, tor_cmd: &str) -> &mut Self {
|
||||
self.tor_cmd = tor_cmd.to_string();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn torrc_path(&mut self, torrc_path: &str) -> &mut Self {
|
||||
self.torrc_path = Some(torrc_path.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn arg(&mut self, arg: String) -> &mut Self {
|
||||
self.args.push(arg);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn args(&mut self, args: Vec<String>) -> &mut Self {
|
||||
for arg in args {
|
||||
self.arg(arg);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn completion_percent(&mut self, completion_percent: u8) -> &mut Self {
|
||||
self.completion_percent = completion_percent;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn timeout(&mut self, timeout: u32) -> &mut Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn working_dir(&mut self, dir: &str) -> &mut Self {
|
||||
self.working_dir = Some(dir.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
// The tor process will have its stdout piped, so if the stdout lines are not consumed they
|
||||
// will keep accumulating over time, increasing the consumed memory.
|
||||
pub fn launch(&mut self) -> Result<&mut Self, Error> {
|
||||
let mut tor = Command::new(&self.tor_cmd);
|
||||
|
||||
if let Some(ref d) = self.working_dir {
|
||||
tor.current_dir(&d);
|
||||
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(Error::IO)?;
|
||||
let pid = pid
|
||||
.parse::<i32>()
|
||||
.map_err(|err| Error::PID(format!("{:?}", err)))?;
|
||||
if let Some(p) = self.get_process(pid) {
|
||||
let _ = p.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ref torrc_path) = self.torrc_path {
|
||||
tor.args(&vec!["-f", torrc_path]);
|
||||
}
|
||||
let mut tor_process = tor
|
||||
.args(&self.args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|err| {
|
||||
let msg = format!("TOR executable (`{}`) not found. Please ensure TOR is installed and on the path: {:?}", TOR_EXE_NAME, err);
|
||||
Error::Process(msg)
|
||||
})?;
|
||||
|
||||
if let Some(ref d) = self.working_dir {
|
||||
// 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(Error::IO)?;
|
||||
file.write_all(format!("{}", tor_process.id()).as_bytes())
|
||||
.map_err(Error::IO)?;
|
||||
}
|
||||
|
||||
let stdout = BufReader::new(tor_process.stdout.take().unwrap());
|
||||
|
||||
self.process = Some(tor_process);
|
||||
let completion_percent = self.completion_percent;
|
||||
|
||||
let (stdout_tx, stdout_rx) = channel();
|
||||
let stdout_timeout_tx = stdout_tx.clone();
|
||||
|
||||
let timer = timer::Timer::new();
|
||||
let _guard =
|
||||
timer.schedule_with_delay(chrono::Duration::seconds(self.timeout as i64), move || {
|
||||
stdout_timeout_tx.send(Err(Error::Timeout)).unwrap_or(());
|
||||
});
|
||||
let stdout_thread = thread::spawn(move || {
|
||||
stdout_tx
|
||||
.send(Self::parse_tor_stdout(stdout, completion_percent))
|
||||
.unwrap_or(());
|
||||
});
|
||||
match stdout_rx.recv().unwrap() {
|
||||
Ok(stdout) => {
|
||||
stdout_thread.join().unwrap();
|
||||
self.stdout = Some(stdout);
|
||||
Ok(self)
|
||||
}
|
||||
Err(err) => {
|
||||
self.kill().unwrap_or(());
|
||||
stdout_thread.join().unwrap();
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_tor_stdout(
|
||||
mut stdout: BufReader<ChildStdout>,
|
||||
completion_perc: u8,
|
||||
) -> Result<BufReader<ChildStdout>, Error> {
|
||||
let re_bootstrap = Regex::new(r"^\[notice\] Bootstrapped (?P<perc>[0-9]+)%(.*): ")
|
||||
.map_err(Error::Regex)?;
|
||||
|
||||
let timestamp_len = "May 16 02:50:08.792".len();
|
||||
let mut warnings = Vec::new();
|
||||
let mut raw_line = String::new();
|
||||
|
||||
while stdout
|
||||
.read_line(&mut raw_line)
|
||||
.map_err(|err| Error::Process(format!("{}", err)))?
|
||||
> 0
|
||||
{
|
||||
{
|
||||
if raw_line.len() < timestamp_len + 1 {
|
||||
return Err(Error::InvalidLogLine);
|
||||
}
|
||||
let timestamp = &raw_line[..timestamp_len];
|
||||
let line = &raw_line[timestamp_len + 1..raw_line.len() - 1];
|
||||
debug!("{} {}", timestamp, line);
|
||||
match line.split(' ').nth(0) {
|
||||
Some("[notice]") => {
|
||||
if let Some("Bootstrapped") = line.split(' ').nth(1) {
|
||||
let perc = re_bootstrap
|
||||
.captures(line)
|
||||
.and_then(|c| c.name("perc"))
|
||||
.and_then(|pc| pc.as_str().parse::<u8>().ok())
|
||||
.ok_or_else(|| Error::InvalidBootstrapLine(line.to_string()))?;
|
||||
|
||||
if perc >= completion_perc {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("[warn]") => warnings.push(line.to_string()),
|
||||
Some("[err]") => return Err(Error::Tor(line.to_string(), warnings)),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
raw_line.clear();
|
||||
}
|
||||
Ok(stdout)
|
||||
}
|
||||
|
||||
pub fn kill(&mut self) -> Result<(), Error> {
|
||||
if let Some(ref mut process) = self.process {
|
||||
Ok(process
|
||||
.kill()
|
||||
.map_err(|err| Error::Process(format!("{}", err)))?)
|
||||
} else {
|
||||
Err(Error::ProcessNotStarted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TorProcess {
|
||||
// kill the child
|
||||
fn drop(&mut self) {
|
||||
debug!("Dropping TOR process");
|
||||
self.kill().unwrap_or(());
|
||||
}
|
||||
}
|
||||
|
||||
+191
-191
@@ -1,191 +1,191 @@
|
||||
// Copyright 2022 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::Error;
|
||||
use grin_wallet_config::types::TorProxyConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::str;
|
||||
use url::Host;
|
||||
|
||||
/// Tor Proxy
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TorProxy {
|
||||
/// proxy type used for the proxy, eg "socks4", "socks5", "http", "https"
|
||||
pub transport: Option<String>,
|
||||
/// Proxy address for the proxy, eg IP:PORT or Hostname
|
||||
pub address: Option<String>,
|
||||
/// Username for the proxy authentification
|
||||
pub username: Option<String>,
|
||||
/// Password for the proxy authentification
|
||||
pub password: Option<String>,
|
||||
/// computer goes through a firewall that only allows connections to certain ports
|
||||
pub allowed_port: Option<Vec<u16>>,
|
||||
}
|
||||
|
||||
impl Default for TorProxy {
|
||||
fn default() -> TorProxy {
|
||||
TorProxy {
|
||||
transport: None,
|
||||
address: None,
|
||||
username: None,
|
||||
password: None,
|
||||
allowed_port: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TorProxy {
|
||||
fn parse_host_port(addr: &str) -> Result<(String, Option<String>), Error> {
|
||||
let host: String;
|
||||
let str_port: Option<String>;
|
||||
let address = addr
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect::<String>();
|
||||
if address.starts_with('[') {
|
||||
let split = address.split_once("]:").unwrap();
|
||||
host = split.0.to_string();
|
||||
str_port = Some(split.1.to_string());
|
||||
} else if address.contains(":") && !address.ends_with(":") {
|
||||
let split = address.split_once(":").unwrap();
|
||||
host = split.0.to_string();
|
||||
str_port = Some(split.1.to_string());
|
||||
} else {
|
||||
host = address.to_string();
|
||||
str_port = None;
|
||||
};
|
||||
Ok((host, str_port))
|
||||
}
|
||||
|
||||
pub fn parse_address(addr: &str) -> Result<(String, Option<u16>), Error> {
|
||||
let (host, str_port) = TorProxy::parse_host_port(&addr)?;
|
||||
let host = Host::parse(&host)
|
||||
.map_err(|_e| Error::TorProxy(format!("Invalid host address: {}", host)))?;
|
||||
let port = if let Some(p) = str_port {
|
||||
let res = p
|
||||
.parse::<u16>()
|
||||
.map_err(|_e| Error::TorProxy(format!("Invalid port number: {}", p)))?;
|
||||
Some(res)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((host.to_string(), port))
|
||||
}
|
||||
|
||||
pub fn to_hashmap(self) -> Result<HashMap<String, String>, Error> {
|
||||
let mut hm = HashMap::new();
|
||||
if let Some(ports) = self.allowed_port {
|
||||
let mut allowed_ports = "".to_string();
|
||||
let last_port = ports.last().unwrap().to_owned();
|
||||
for port in ports.clone() {
|
||||
allowed_ports.push_str(format!("*:{}", port).as_str());
|
||||
if port != last_port {
|
||||
allowed_ports.push_str(",");
|
||||
}
|
||||
}
|
||||
hm.insert(
|
||||
"ReachableAddresses".to_string(),
|
||||
format!("{}", allowed_ports.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
let transport = match self.transport {
|
||||
Some(t) => t,
|
||||
None => return Ok(hm),
|
||||
};
|
||||
match transport.as_str() {
|
||||
"socks4" => {
|
||||
hm.insert("Socks4Proxy".to_string(), self.address.unwrap());
|
||||
Ok(hm)
|
||||
}
|
||||
"socks5" => {
|
||||
hm.insert("Socks5Proxy".to_string(), self.address.unwrap());
|
||||
|
||||
if let Some(s) = self.username {
|
||||
hm.insert("Socks5ProxyUsername".to_string(), s);
|
||||
}
|
||||
if let Some(s) = self.password {
|
||||
hm.insert("Socks5ProxyPassword".to_string(), s);
|
||||
}
|
||||
Ok(hm)
|
||||
}
|
||||
"http" | "https" | "http(s)" => {
|
||||
hm.insert("HTTPSProxy".to_string(), self.address.unwrap());
|
||||
|
||||
if let Some(user) = self.username {
|
||||
let pass = self.password.unwrap_or("".to_string());
|
||||
hm.insert(
|
||||
"HTTPSProxyAuthenticator".to_string(),
|
||||
format!("{}:{}", user, pass),
|
||||
);
|
||||
}
|
||||
Ok(hm)
|
||||
}
|
||||
_ => Ok(hm),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<TorProxyConfig> for TorProxy {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(tb: TorProxyConfig) -> Result<Self, Self::Error> {
|
||||
if let Some(t) = tb.transport {
|
||||
let transport = t.to_lowercase();
|
||||
match transport.as_str() {
|
||||
"socks4" | "socks5" | "http" | "https" | "http(s)" => {
|
||||
// Can't parse socket address --> trying to parse a domain name
|
||||
if let Some(address) = tb.address {
|
||||
let address_addr: String;
|
||||
let (host, port) = TorProxy::parse_address(&address)?;
|
||||
if let Some(p) = port {
|
||||
address_addr = format!("{}:{}", host, p);
|
||||
} else {
|
||||
address_addr = host
|
||||
}
|
||||
Ok(TorProxy {
|
||||
transport: Some(transport.into()),
|
||||
address: Some(address_addr),
|
||||
username: tb.username,
|
||||
password: tb.password,
|
||||
allowed_port: tb.allowed_port,
|
||||
})
|
||||
} else {
|
||||
let msg = format!(
|
||||
"Missing proxy address: {} - must be <IP:PORT> or <Hostname>",
|
||||
transport
|
||||
);
|
||||
return Err(Error::TorProxy(msg).into());
|
||||
}
|
||||
}
|
||||
// Missing transport type
|
||||
_ => {
|
||||
let msg = format!(
|
||||
"Invalid proxy transport: {} - must be socks4/socks5/http(s)",
|
||||
transport
|
||||
);
|
||||
Err(Error::TorProxy(msg).into())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// In case the user want to allow only some ports
|
||||
let ports = tb.allowed_port.unwrap();
|
||||
Ok(TorProxy {
|
||||
allowed_port: Some(ports),
|
||||
..TorProxy::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
// Copyright 2022 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::Error;
|
||||
use grin_wallet_config::types::TorProxyConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::str;
|
||||
use url::Host;
|
||||
|
||||
/// Tor Proxy
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TorProxy {
|
||||
/// proxy type used for the proxy, eg "socks4", "socks5", "http", "https"
|
||||
pub transport: Option<String>,
|
||||
/// Proxy address for the proxy, eg IP:PORT or Hostname
|
||||
pub address: Option<String>,
|
||||
/// Username for the proxy authentification
|
||||
pub username: Option<String>,
|
||||
/// Password for the proxy authentification
|
||||
pub password: Option<String>,
|
||||
/// computer goes through a firewall that only allows connections to certain ports
|
||||
pub allowed_port: Option<Vec<u16>>,
|
||||
}
|
||||
|
||||
impl Default for TorProxy {
|
||||
fn default() -> TorProxy {
|
||||
TorProxy {
|
||||
transport: None,
|
||||
address: None,
|
||||
username: None,
|
||||
password: None,
|
||||
allowed_port: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TorProxy {
|
||||
fn parse_host_port(addr: &str) -> Result<(String, Option<String>), Error> {
|
||||
let host: String;
|
||||
let str_port: Option<String>;
|
||||
let address = addr
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect::<String>();
|
||||
if address.starts_with('[') {
|
||||
let split = address.split_once("]:").unwrap();
|
||||
host = split.0.to_string();
|
||||
str_port = Some(split.1.to_string());
|
||||
} else if address.contains(":") && !address.ends_with(":") {
|
||||
let split = address.split_once(":").unwrap();
|
||||
host = split.0.to_string();
|
||||
str_port = Some(split.1.to_string());
|
||||
} else {
|
||||
host = address.to_string();
|
||||
str_port = None;
|
||||
};
|
||||
Ok((host, str_port))
|
||||
}
|
||||
|
||||
pub fn parse_address(addr: &str) -> Result<(String, Option<u16>), Error> {
|
||||
let (host, str_port) = TorProxy::parse_host_port(&addr)?;
|
||||
let host = Host::parse(&host)
|
||||
.map_err(|_e| Error::TorProxy(format!("Invalid host address: {}", host)))?;
|
||||
let port = if let Some(p) = str_port {
|
||||
let res = p
|
||||
.parse::<u16>()
|
||||
.map_err(|_e| Error::TorProxy(format!("Invalid port number: {}", p)))?;
|
||||
Some(res)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((host.to_string(), port))
|
||||
}
|
||||
|
||||
pub fn to_hashmap(self) -> Result<HashMap<String, String>, Error> {
|
||||
let mut hm = HashMap::new();
|
||||
if let Some(ports) = self.allowed_port {
|
||||
let mut allowed_ports = "".to_string();
|
||||
let last_port = ports.last().unwrap().to_owned();
|
||||
for port in ports.clone() {
|
||||
allowed_ports.push_str(format!("*:{}", port).as_str());
|
||||
if port != last_port {
|
||||
allowed_ports.push_str(",");
|
||||
}
|
||||
}
|
||||
hm.insert(
|
||||
"ReachableAddresses".to_string(),
|
||||
format!("{}", allowed_ports.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
let transport = match self.transport {
|
||||
Some(t) => t,
|
||||
None => return Ok(hm),
|
||||
};
|
||||
match transport.as_str() {
|
||||
"socks4" => {
|
||||
hm.insert("Socks4Proxy".to_string(), self.address.unwrap());
|
||||
Ok(hm)
|
||||
}
|
||||
"socks5" => {
|
||||
hm.insert("Socks5Proxy".to_string(), self.address.unwrap());
|
||||
|
||||
if let Some(s) = self.username {
|
||||
hm.insert("Socks5ProxyUsername".to_string(), s);
|
||||
}
|
||||
if let Some(s) = self.password {
|
||||
hm.insert("Socks5ProxyPassword".to_string(), s);
|
||||
}
|
||||
Ok(hm)
|
||||
}
|
||||
"http" | "https" | "http(s)" => {
|
||||
hm.insert("HTTPSProxy".to_string(), self.address.unwrap());
|
||||
|
||||
if let Some(user) = self.username {
|
||||
let pass = self.password.unwrap_or("".to_string());
|
||||
hm.insert(
|
||||
"HTTPSProxyAuthenticator".to_string(),
|
||||
format!("{}:{}", user, pass),
|
||||
);
|
||||
}
|
||||
Ok(hm)
|
||||
}
|
||||
_ => Ok(hm),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<TorProxyConfig> for TorProxy {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(tb: TorProxyConfig) -> Result<Self, Self::Error> {
|
||||
if let Some(t) = tb.transport {
|
||||
let transport = t.to_lowercase();
|
||||
match transport.as_str() {
|
||||
"socks4" | "socks5" | "http" | "https" | "http(s)" => {
|
||||
// Can't parse socket address --> trying to parse a domain name
|
||||
if let Some(address) = tb.address {
|
||||
let address_addr: String;
|
||||
let (host, port) = TorProxy::parse_address(&address)?;
|
||||
if let Some(p) = port {
|
||||
address_addr = format!("{}:{}", host, p);
|
||||
} else {
|
||||
address_addr = host
|
||||
}
|
||||
Ok(TorProxy {
|
||||
transport: Some(transport.into()),
|
||||
address: Some(address_addr),
|
||||
username: tb.username,
|
||||
password: tb.password,
|
||||
allowed_port: tb.allowed_port,
|
||||
})
|
||||
} else {
|
||||
let msg = format!(
|
||||
"Missing proxy address: {} - must be <IP:PORT> or <Hostname>",
|
||||
transport
|
||||
);
|
||||
return Err(Error::TorProxy(msg).into());
|
||||
}
|
||||
}
|
||||
// Missing transport type
|
||||
_ => {
|
||||
let msg = format!(
|
||||
"Invalid proxy transport: {} - must be socks4/socks5/http(s)",
|
||||
transport
|
||||
);
|
||||
Err(Error::TorProxy(msg).into())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// In case the user want to allow only some ports
|
||||
let ports = tb.allowed_port.unwrap();
|
||||
Ok(TorProxy {
|
||||
allowed_port: Some(ports),
|
||||
..TorProxy::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user