merge staging

This commit is contained in:
wiesche
2026-10-17 07:52:36 +02:00
137 changed files with 7846 additions and 7319 deletions
+18 -18
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_impls"
version = "5.5.0"
version = "5.5.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Concrete types derived from libwallet traits"
license = "Apache-2.0"
@@ -32,31 +32,31 @@ sysinfo = "0.29"
base64 = "0.12.0"
url = "2.1"
arti-client = { version = "0.44.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] }
tor-rtcompat = { version = "0.44.0", features = ["static"] }
fs-mistrust = "0.15.0"
arti-client = { version = "0.43.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] }
tor-rtcompat = { version = "0.43.0", features = ["static"] }
fs-mistrust = "0.14.2"
fslock-guard = "0.8"
tor-hsservice = "0.44.0"
tor-hsrproxy = "0.44.0"
tor-keymgr = "0.44.0"
tor-llcrypto = "0.44.0"
tor-hscrypto = "0.44.0"
tor-hsservice = "0.43.0"
tor-hsrproxy = "0.43.0"
tor-keymgr = "0.43.0"
tor-llcrypto = "0.43.0"
tor-hscrypto = "0.43.0"
sha2 = "0.10.8"
hyper = { version = "1.10.1", features = ["http1", "client"] }
hyper-util = { version = "0.1.20", features = ["tokio"] }
http-body-util = "0.1.3"
bytes = "1.11.1"
grin_wallet_util = { path = "../util", version = "5.5.0" }
grin_wallet_config = { path = "../config", version = "5.5.0" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" }
grin_wallet_util = { path = "../util", version = "5.5.1" }
grin_wallet_config = { path = "../config", version = "5.5.1" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" }
##### Grin Imports
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_core = { workspace = true }
grin_keychain = { workspace = true }
grin_chain = { workspace = true }
grin_util = { workspace = true }
grin_api = { workspace = true }
#####
#####
-2
View File
@@ -13,11 +13,9 @@
// limitations under the License.
mod file;
mod slatepack;
pub mod tor;
pub use self::file::PathToSlate;
pub use self::slatepack::PathToSlatepack;
pub use self::tor::TorSlateSender;
use crate::config::WalletConfig;
-179
View File
@@ -1,179 +0,0 @@
// Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// 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 _ = fs::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());
}
}
+6 -7
View File
@@ -27,7 +27,7 @@ use serde_json::{json, Value};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Clone)]
@@ -65,7 +65,7 @@ impl TorSlateSender {
}
/// Launch external Tor process.
fn launch_tor_process(config: &TorConfig, tor_dir: &PathBuf) -> Result<TorProcess, Error> {
fn launch_tor_process(config: &TorConfig, tor_dir: &Path) -> Result<TorProcess, Error> {
let mut tor = TorProcess::new();
let socks_proxy_addr = SocketAddr::V4(
config
@@ -101,7 +101,7 @@ impl TorSlateSender {
)
.map_err(|e| Error::TorConfig(format!("{:?}", e)))?;
// Start TOR process
let mut path = tor_dir.clone();
let mut path = tor_dir.to_path_buf();
path.push("torrc");
tor.torrc_path(path.to_str().unwrap())
.working_dir(tor_dir.to_str().unwrap())
@@ -124,7 +124,7 @@ impl TorSlateSender {
let res: String = self.post(url, 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") {
if !self.config.use_integrated.unwrap_or(false) && 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."
@@ -178,11 +178,10 @@ impl TorSlateSender {
let client = Client::with_proxy(socks_proxy_addr, "socks5h://", timeout)
.map_err(|_| ClientError::Internal("Unable to create http client".into()))?;
let req = client.create_post_request(url, None, &input)?;
let res = client.send_request(req)?;
res
client.send_request(req)?
} else {
tor_post(&self.config, &input, url)
.map_err(|e| ClientError::RequestError(format!("{:?}", e)))?
.map_err(|e| ClientError::RequestError(e.to_string()))?
};
Ok(res)
}
+62 -12
View File
@@ -19,7 +19,6 @@ 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;
use std::time::Duration;
@@ -32,6 +31,7 @@ lazy_static! {
}
#[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum Error {
#[error("Internal error: {0}")]
Internal(String),
@@ -76,7 +76,7 @@ impl Client {
if let Some(p) = proxy {
let (addr, scheme) = p;
let proxy = Proxy::all(&format!("{}{}:{}", scheme, addr.ip(), addr.port()))
let proxy = Proxy::all(format!("{}{}:{}", scheme, addr.ip(), addr.port()))
.map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?;
builder = builder.proxy(proxy);
}
@@ -91,7 +91,7 @@ impl 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>
pub fn _get<T>(&self, url: &str, api_secret: Option<String>) -> Result<T, Error>
where
for<'de> T: Deserialize<'de>,
{
@@ -101,11 +101,7 @@ impl Client {
/// 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>
pub async fn _get_async<T>(&self, url: &str, api_secret: Option<String>) -> Result<T, Error>
where
for<'de> T: Deserialize<'de> + Send + 'static,
{
@@ -225,7 +221,7 @@ impl Client {
IN: Serialize,
{
let json = serde_json::to_string(input)
.map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?;
.map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?;
self.build_request(url, Method::POST, api_secret, Some(json))
}
@@ -235,7 +231,7 @@ impl Client {
{
let data = self.send_request(req)?;
serde_json::from_str(&data)
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))
.map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))
}
async fn handle_request_async<T>(&self, req: RequestBuilder) -> Result<T, Error>
@@ -244,7 +240,7 @@ impl Client {
{
let data = self.send_request_async(req).await?;
let ser = serde_json::from_str(&data)
.map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?;
.map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?;
Ok(ser)
}
@@ -253,6 +249,10 @@ impl Client {
.send()
.await
.map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?;
let status = resp.status();
if status.is_client_error() || status.is_server_error() {
return Err(Error::ResponseError(format!("HTTP {}", status)));
}
let text = resp
.text()
.await
@@ -261,7 +261,7 @@ impl Client {
}
pub fn send_request(&self, req: RequestBuilder) -> Result<String, Error> {
// This client is currently used both outside and inside of a tokio runtime
// This client is currently used both outside and inside the 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() {
@@ -275,3 +275,53 @@ impl Client {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
#[tokio::test]
async fn http_status() {
let client = Client {
client: ClientBuilder::new()
.no_proxy()
.timeout(Duration::from_secs(5))
.build()
.unwrap(),
};
for (status, body, expected) in [
("200 OK", "{}", Ok(serde_json::json!({}))),
(
"401 Unauthorized",
"<html>Unauthorized</html>",
Err(Error::ResponseError("HTTP 401 Unauthorized".into())),
),
] {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut headers = BufReader::new(&mut stream).lines();
while let Some(line) = headers.next_line().await.unwrap() {
if line.is_empty() {
break;
}
}
let response = format!(
"HTTP/1.1 {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
status,
body.len(),
body
);
stream.write_all(response.as_bytes()).await.unwrap();
});
assert_eq!(
client._get_async::<serde_json::Value>(&url, None).await,
expected
);
server.await.unwrap();
}
}
}
+9 -9
View File
@@ -22,7 +22,7 @@ use serde_json;
pub fn build_request<'a, 'b>(name: &'a str, params: &'b serde_json::Value) -> Request<'a, 'b> {
Request {
method: name,
params: params,
params,
id: From::from(1),
jsonrpc: Some("2.0"),
}
@@ -133,7 +133,7 @@ impl fmt::Display for Error {
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)),
ref e => write!(f, "{:?}", e),
}
}
}
@@ -217,27 +217,27 @@ pub fn _standard_error(code: StandardError, data: Option<serde_json::Value>) ->
StandardError::ParseError => RpcError {
code: -32700,
message: "Parse error".to_string(),
data: data,
data,
},
StandardError::InvalidRequest => RpcError {
code: -32600,
message: "Invalid Request".to_string(),
data: data,
data,
},
StandardError::MethodNotFound => RpcError {
code: -32601,
message: "Method not found".to_string(),
data: data,
data,
},
StandardError::InvalidParams => RpcError {
code: -32602,
message: "Invalid params".to_string(),
data: data,
data,
},
StandardError::InternalError => RpcError {
code: -32603,
message: "Internal error".to_string(),
data: data,
data,
},
}
}
@@ -251,13 +251,13 @@ pub fn _result_to_response(
Ok(data) => Response {
result: Some(data),
error: None,
id: id,
id,
jsonrpc: Some(String::from("2.0")),
},
Err(err) => Response {
result: None,
error: Some(err),
id: id,
id,
jsonrpc: Some(String::from("2.0")),
},
}
+2 -2
View File
@@ -75,8 +75,8 @@ pub enum Error {
Encryption,
/// BIP 39 word list
#[error("BIP39 Mnemonic (word list) Error")]
Mnemonic,
#[error("BIP39 Mnemonic (word list) Error: {}", _0)]
Mnemonic(String),
/// Command line argument error
#[error("{}", _0)]
+2 -2
View File
@@ -42,9 +42,9 @@ pub mod test_framework;
pub mod tor;
pub use crate::adapters::{
PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver, SlateSender,
TorSlateSender,
PathToSlate, SlateGetter, SlatePutter, SlateReceiver, SlateSender, TorSlateSender,
};
pub use crate::client_utils::json_rpc;
pub use crate::error::Error;
pub use crate::lifecycle::DefaultLCProvider;
pub use crate::node_clients::HTTPNodeClient;
+113 -19
View File
@@ -32,9 +32,7 @@ use std::path::MAIN_SEPARATOR;
/// Helper function 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
path.replace("/", sep).replace("\\", sep)
}
pub struct DefaultLCProvider<C, K>
@@ -77,8 +75,8 @@ where
let data_dir = self
.data_dir
.to_owned()
.replace("/", &sep)
.replace("\\", &sep);
.replace("/", sep)
.replace("\\", sep);
Ok(data_dir)
}
@@ -108,7 +106,7 @@ where
return Ok(());
}
let mut default_config = GlobalWalletConfig::for_chain(&chain_type, &config_file_name);
let mut default_config = GlobalWalletConfig::for_chain(chain_type, &config_file_name);
let config_file_version = default_config.members.config_file_version;
let logging = match logging_config.clone() {
Some(l) => Some(l),
@@ -140,7 +138,7 @@ where
absolute_path_wallet.push(self.data_dir.clone());
// if no config provided, update defaults
if update == true {
if update {
// create top level dir if it doesn't exist
let dd = PathBuf::from(self.data_dir.clone());
if !dd.exists() {
@@ -182,7 +180,7 @@ where
&mut self,
_name: Option<&str>,
mnemonic: Option<ZeroingString>,
mnemonic_length: usize,
entropy_size: usize,
password: ZeroingString,
test_mode: bool,
) -> Result<(), Error> {
@@ -196,23 +194,22 @@ where
return Err(Error::WalletSeedExists(msg));
}
}
let entropy_size = if entropy_size == 0 { 32 } else { entropy_size };
WalletSeed::init_file(
&data_dir_name,
mnemonic_length,
entropy_size,
mnemonic.clone(),
password,
test_mode,
)
.map_err(|_| {
Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned())
})?;
.map_err(|e| Error::Lifecycle(format!("Error creating wallet seed: {}", e)))?;
info!("Wallet seed file created");
let mut wallet: WalletBackend<C, K> =
match WalletBackend::new(&data_dir_name, self.node_client.clone()) {
Err(e) => {
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name);
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, data_dir_name);
error!("{}", msg);
return Err(Error::Lifecycle(msg).into());
return Err(Error::Lifecycle(msg));
}
Ok(d) => d,
};
@@ -240,7 +237,7 @@ where
let mut wallet: WalletBackend<C, K> =
match WalletBackend::new(&data_dir_name, self.node_client.clone()) {
Err(e) => {
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name);
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, data_dir_name);
return Err(Error::Lifecycle(msg));
}
Ok(d) => d,
@@ -248,6 +245,9 @@ where
let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| {
Error::Lifecycle("Error opening wallet (is password correct?)".to_owned())
})?;
if wallet_seed.is_empty() {
warn!("This wallet has an empty seed and its funds are unsafe. Move them to a new wallet.");
}
let keychain = wallet_seed
.derive_keychain(global::is_testnet())
.map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?;
@@ -269,7 +269,7 @@ where
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)
let res = WalletSeed::seed_file_exists(data_dir_name)
.map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?;
Ok(res)
}
@@ -286,7 +286,7 @@ where
.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()))?;
.map_err(|e| Error::Lifecycle(format!("Error recovering wallet seed: {}. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.", e)))?;
Ok(ZeroingString::from(res))
}
@@ -320,7 +320,7 @@ where
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)
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()
@@ -346,7 +346,7 @@ where
);
info!("Wallet seed file created");
let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new)
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 {
@@ -382,3 +382,97 @@ where
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keychain::ExtKeychain;
use crate::lifecycle::seed::{EncryptedWalletSeed, SEED_FILE};
use crate::node_clients::HTTPNodeClient;
use std::fs::File;
use std::io::Write;
use std::time::Duration;
fn provider(test_dir: &str) -> DefaultLCProvider<HTTPNodeClient, ExtKeychain> {
let client =
HTTPNodeClient::new("http://127.0.0.1:1", None, Duration::from_secs(1)).unwrap();
let mut provider = DefaultLCProvider::new(client);
provider.set_top_level_directory(test_dir).unwrap();
provider
}
#[test]
fn default_recovery_phrase() {
let test_dir = "test_output/default_recovery_phrase";
let _ = fs::remove_dir_all(test_dir);
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let mut provider = provider(test_dir);
let password = ZeroingString::from("test");
provider
.create_wallet(None, None, 0, password.clone(), false)
.unwrap();
let mnemonic = provider.get_mnemonic(None, password).unwrap();
assert_eq!(mnemonic.split_whitespace().count(), 24);
fs::remove_dir_all(test_dir).unwrap();
}
#[test]
fn mnemonic_error_redacted() {
let test_dir = "test_output/mnemonic_error_redacted";
let _ = fs::remove_dir_all(test_dir);
let mut provider = provider(test_dir);
let input = ZeroingString::from("INVALID_INPUT_MARKER ".repeat(12));
let error = provider
.create_wallet(None, Some(input), 32, ZeroingString::from("test"), false)
.unwrap_err()
.to_string();
assert!(error.contains("invalid bip39 word"));
assert!(!error.contains("INVALID_INPUT_MARKER"));
assert!(!provider.wallet_exists(None).unwrap());
fs::remove_dir_all(test_dir).unwrap();
}
#[test]
fn missing_recovery_phrase() {
let test_dir = "test_output/missing_recovery_phrase";
let _ = fs::remove_dir_all(test_dir);
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let mut provider = provider(test_dir);
let password = ZeroingString::from("test");
let data_dir = PathBuf::from(test_dir).join(GRIN_WALLET_DIR);
fs::create_dir_all(data_dir.clone()).unwrap();
let seed_file_path = &format!(
"{}{}{}",
fmt_path(data_dir.to_str().unwrap().to_string()),
MAIN_SEPARATOR,
SEED_FILE,
);
let enc_seed = EncryptedWalletSeed::from_seed(
&WalletSeed::from_bytes(vec![].as_slice()),
password.clone(),
)
.unwrap();
let enc_seed_json = serde_json::to_string_pretty(&enc_seed).unwrap();
let mut file = File::create(seed_file_path).unwrap();
file.write_all(enc_seed_json.as_bytes()).unwrap();
let error = match provider.get_mnemonic(None, password.clone()) {
Ok(_) => panic!("expected missing recovery phrase error"),
Err(error) => error,
};
assert_eq!(
error,
Error::Lifecycle("Error recovering wallet seed: BIP39 Mnemonic (word list) Error: invalid mnemonic/entropy length 0. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.".into())
);
provider.open_wallet(None, password, false, false).unwrap();
provider.close_wallet(None).unwrap();
assert_eq!(fs::read_to_string(seed_file_path).unwrap(), enc_seed_json);
fs::remove_dir_all(test_dir).unwrap();
}
}
+35 -21
View File
@@ -15,7 +15,6 @@
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;
@@ -39,17 +38,24 @@ impl WalletSeed {
WalletSeed(bytes.to_vec())
}
pub(super) fn is_empty(&self) -> bool {
self.0.is_empty()
}
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()),
Err(mnemonic::Error::BadWord(_)) => {
Err(Error::Mnemonic("invalid bip39 word".to_owned()))
}
Err(e) => Err(Error::Mnemonic(format!("{}", e))),
}
}
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()))?;
let bytes =
util::from_hex(hex).map_err(|_| Error::GenericError("Invalid hex".to_owned()))?;
Ok(WalletSeed::from_bytes(&bytes))
}
@@ -61,7 +67,7 @@ impl WalletSeed {
let result = mnemonic::from_entropy(&self.0);
match result {
Ok(r) => Ok(r),
Err(_) => Err(Error::Mnemonic.into()),
Err(e) => Err(Error::Mnemonic(format!("{}", e))),
}
}
@@ -76,14 +82,14 @@ impl WalletSeed {
}
pub fn init_new(
seed_length: usize,
entropy_size: usize,
test_mode: bool,
password: Option<util::ZeroingString>,
) -> WalletSeed {
) -> Result<WalletSeed, Error> {
let mut seed: Vec<u8> = vec![];
let mut rng = thread_rng();
if !test_mode {
for _ in 0..seed_length {
for _ in 0..entropy_size {
seed.push(rng.gen());
}
} else {
@@ -93,7 +99,10 @@ impl WalletSeed {
.as_bytes()
.to_vec();
}
WalletSeed(seed)
let _ = mnemonic::from_entropy(seed.as_slice())
.map(util::ZeroingString::from)
.map_err(|e| Error::Mnemonic(format!("{}", e)))?;
Ok(WalletSeed(seed))
}
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
@@ -126,7 +135,9 @@ impl WalletSeed {
}
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());
return Err(Error::GenericError(
"Can't rename wallet seed file".to_owned(),
));
}
warn!("{} backed up as {}", seed_file_name, backup_seed_file_name);
Ok(backup_seed_file_name)
@@ -153,14 +164,13 @@ impl WalletSeed {
data_file_dir.to_owned(),
"To create a new wallet from a recovery phrase, use 'grin-wallet init -r'"
.to_owned(),
)
.into());
));
}
let seed = WalletSeed::from_mnemonic(word_list)?;
let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?;
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())
file.write_all(enc_seed_json.as_bytes())
.map_err(|_| Error::IO)?;
warn!("Seed created from word list");
Ok(())
@@ -168,7 +178,7 @@ impl WalletSeed {
pub fn init_file(
data_file_dir: &str,
seed_length: usize,
entropy_size: usize,
recovery_phrase: Option<util::ZeroingString>,
password: util::ZeroingString,
test_mode: bool,
@@ -193,13 +203,13 @@ impl WalletSeed {
let seed = match recovery_phrase {
Some(p) => WalletSeed::from_mnemonic(p)?,
None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())),
None => WalletSeed::init_new(entropy_size, 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())
file.write_all(enc_seed_json.as_bytes())
.map_err(|_| Error::IO)?;
Ok(seed)
}
@@ -277,7 +287,7 @@ impl EncryptedWalletSeed {
let password = password.as_bytes();
let mut key = [0; 32];
pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA512,
pbkdf2::PBKDF2_HMAC_SHA512,
NonZeroU32::new(100).unwrap(),
&salt,
password,
@@ -297,7 +307,7 @@ impl EncryptedWalletSeed {
aad,
&mut enc_bytes,
);
if let Err(_) = res {
if res.is_err() {
return Err(Error::Encryption);
}
@@ -325,7 +335,7 @@ impl EncryptedWalletSeed {
let password = password.as_bytes();
let mut key = [0; 32];
pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA512,
pbkdf2::PBKDF2_HMAC_SHA512,
NonZeroU32::new(100).unwrap(),
&salt,
password,
@@ -342,7 +352,7 @@ impl EncryptedWalletSeed {
aad,
&mut encrypted_seed,
);
if let Err(_) = res {
if res.is_err() {
return Err(Error::Encryption);
}
for _ in 0..aead::AES_256_GCM.tag_len() {
@@ -359,8 +369,12 @@ mod tests {
use crate::util::ZeroingString;
#[test]
fn wallet_seed_encrypt() {
// Wrong entropy size.
let wrong_entropy_size = WalletSeed::init_new(31, false, None).err();
assert!(wrong_entropy_size.is_some());
let password = ZeroingString::from("passwoid");
let wallet_seed = WalletSeed::init_new(32, false, None);
let wallet_seed = WalletSeed::init_new(32, false, None).unwrap();
let mut enc_wallet_seed =
EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap();
println!("EWS: {:?}", enc_wallet_seed);
+11 -19
View File
@@ -142,19 +142,12 @@ impl NodeClient for HTTPNodeClient {
},
Err(e) => {
// If node isn't available, allow offline functions
// unfortunately have to parse string due to error structure
let err_string = format!("{}", e);
return if err_string.contains("404") {
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");
None
};
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());
@@ -220,7 +213,7 @@ impl NodeClient for HTTPNodeClient {
// build vec of commits for inclusion in query
let query_params: Vec<String> = wallet_outputs
.iter()
.map(|commit| format!("{}", commit.as_ref().to_hex()))
.map(|commit| commit.as_ref().to_hex())
.collect();
// going to leave this here even though we're moving
@@ -283,10 +276,9 @@ impl NodeClient for HTTPNodeClient {
};
let rt = RUNTIME.clone();
let res: Result<Vec<_>, _> =
std::thread::spawn(move || rt.block_on(async move { task.await }))
.join()
.unwrap();
let res: Result<Vec<_>, _> = std::thread::spawn(move || rt.block_on(task))
.join()
.unwrap();
let results: Vec<OutputPrintable> = match res {
Ok(resps) => {
@@ -345,7 +337,7 @@ impl NodeClient for HTTPNodeClient {
let params = json!([start_index, end_index, max_outputs, Some(true)]);
let res = self.send_json_request::<OutputListing>("get_unspent_outputs", &params)?;
// 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) {
for out in res.outputs.into_iter().filter(|out| !out.spent) {
let is_coinbase = match out.output_type {
api::OutputType::Coinbase => true,
api::OutputType::Transaction => false,
+7 -10
View File
@@ -20,12 +20,9 @@ use crate::core::core::{Output, Transaction, TxKernel};
use crate::core::{consensus, global, pow};
use crate::libwallet;
use crate::libwallet::api_impl::{foreign, owner};
use crate::libwallet::{
BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletInst, WalletLCProvider,
};
use crate::libwallet::{BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletLCProvider};
use crate::util::secp::key::SecretKey;
use crate::util::secp::pedersen;
use crate::util::Mutex;
use chrono::Duration;
use grin_keychain::Keychain;
use std::sync::Arc;
@@ -54,7 +51,7 @@ fn get_kernel_local(
max_height: Option<u64>,
) -> Option<api::LocatedTxKernel> {
chain
.get_kernel_height(&excess, min_height, max_height)
.get_kernel_height(excess, min_height, max_height)
.unwrap()
.map(|(tx_kernel, height, mmr_index)| api::LocatedTxKernel {
tx_kernel,
@@ -147,7 +144,7 @@ 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>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<&SecretKey>,
) -> Result<core::core::Block, libwallet::Error>
where
@@ -178,7 +175,7 @@ where
pub fn award_block_to_wallet<'a, L, C, K>(
chain: &Chain,
txs: &[Transaction],
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<&SecretKey>,
) -> Result<(), libwallet::Error>
where
@@ -200,7 +197,7 @@ pub fn process_block(chain: &Chain, block: core::core::Block) {
/// 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>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<&SecretKey>,
number: usize,
pause_between: bool,
@@ -221,7 +218,7 @@ where
/// 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>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<&SecretKey>,
client: LocalWalletClient,
dest: &str,
@@ -261,7 +258,7 @@ where
/// get wallet info totals
pub fn wallet_info<'a, L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<&SecretKey>,
) -> Result<WalletInfo, libwallet::Error>
where
+6 -10
View File
@@ -26,7 +26,7 @@ use crate::keychain::Keychain;
use crate::libwallet;
use crate::libwallet::api_impl::foreign;
use crate::libwallet::slate_versions::v4::SlateV4;
use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletInst, WalletLCProvider};
use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletLCProvider};
use crate::util;
use crate::util::secp::key::SecretKey;
use crate::util::secp::pedersen;
@@ -66,11 +66,12 @@ where
/// handle to chain itself
pub chain: Arc<Chain>,
/// list of interested wallets
#[allow(clippy::type_complexity)]
pub wallets: HashMap<
String,
(
Sender<WalletProxyMessage>,
Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
Option<SecretKey>,
),
>,
@@ -119,7 +120,7 @@ where
&mut self,
addr: &str,
tx: Sender<WalletProxyMessage>,
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>,
keychain_mask: Option<SecretKey>,
) {
self.wallets
@@ -185,12 +186,7 @@ where
libwallet::Error::ClientCallback("Error parsing Transaction".to_owned())
})?;
super::award_block_to_wallet(
&self.chain,
&[tx],
dest_wallet,
(&dest_wallet_mask).as_ref(),
)?;
super::award_block_to_wallet(&self.chain, &[tx], dest_wallet, dest_wallet_mask.as_ref())?;
Ok(WalletProxyMessage {
sender_id: "node".to_owned(),
@@ -219,7 +215,7 @@ where
let w = w_lock.lc_provider()?.wallet_inst()?;
let mask = wallet.2.clone();
// receive tx
match foreign::receive_tx(w, (&mask).as_ref(), &Slate::from(slate), None, false) {
match foreign::receive_tx(w, mask.as_ref(), &Slate::from(slate), None, false) {
Err(e) => {
return Ok(WalletProxyMessage {
sender_id: m.dest,
+120 -41
View File
@@ -34,6 +34,7 @@ use sha2::Sha512;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
use std::thread::{self, JoinHandle};
use std::time::Duration;
@@ -59,12 +60,26 @@ struct TorService {
state_lock: PathBuf,
}
/// Failure from an HTTP request over Tor, classified by whether delivery may
/// have started.
#[derive(Debug, thiserror::Error)]
pub enum TorPostError {
/// The failure happened before handing the request to Hyper.
#[error("{0}")]
NotSent(Error),
/// Hyper started sending the request, so delivery cannot be ruled out.
#[error("{0}")]
PossiblySent(Error),
}
type ArtiClientConfig = (Arc<TorClient<TokioNativeTlsRuntime>>, TorClientConfig);
lazy_static! {
/// Arti Tokio runtime.
static ref ARTI_RUNTIME: LazyLock<Mutex<Option<ArtiRuntimeWrapper>>> =
LazyLock::new(|| Mutex::new(ArtiRuntimeWrapper::create().ok()));
/// Arti client and config.
static ref ARTI_CLIENT_CONFIG: LazyLock<Mutex<Option<(Arc<TorClient<TokioNativeTlsRuntime>>, TorClientConfig)>>> =
static ref ARTI_CLIENT_CONFIG: LazyLock<Mutex<Option<ArtiClientConfig>>> =
LazyLock::new(|| Mutex::new(None));
/// Running services, where key is onion address.
static ref ARTI_PROXY_SERVICES: LazyLock<Mutex<HashMap<String, TorService>>> =
@@ -138,7 +153,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu
info!("Proxy configuration will be ignored.");
}
let (state_path, cache_path) = state_cache_paths(&config);
let (state_path, cache_path) = state_cache_paths(config);
let (client, config) = init_client(&state_path, &cache_path, config)?;
// Add service key to keystore.
@@ -151,7 +166,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu
let state_lock = state_path
.join("hss")
.join(format!("{}.lock", onion_address));
let _ = add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?;
add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?;
// Launch Onion service.
let service_config = OnionServiceConfigBuilder::default()
@@ -216,39 +231,73 @@ pub fn start_tor_client(config: TorConfig) -> Result<(), Error> {
Ok(())
}
/// Build an origin-form JSON POST request
fn build_post_request(json: String, url: &Uri) -> Result<Request<Full<Bytes>>, Error> {
let authority = url
.authority()
.ok_or_else(|| Error::GenericError(format!("URL {} has bad authority", url)))?;
let request_target = url
.path_and_query()
.map(|path| path.as_str())
.unwrap_or("/");
Request::builder()
.uri(request_target)
.method("POST")
.header("host", authority.as_str())
.header("accept", "application/json")
.header("content-type", "application/json")
.body(Full::from(json))
.map_err(|e| Error::TorProcess(format!("{:?}", e)))
}
/// Make POST request.
pub fn tor_post<IN>(tor_config: &TorConfig, input: &IN, url: &str) -> Result<String, Error>
pub fn tor_post<IN>(tor_config: &TorConfig, input: &IN, url: &str) -> Result<String, TorPostError>
where
IN: Serialize,
{
let json = serde_json::to_string(input)
.map_err(|_| Error::GenericError("Could not serialize data to JSON".to_owned()))?;
let json = serde_json::to_string(input).map_err(|_| {
TorPostError::NotSent(Error::GenericError(
"Could not serialize data to JSON".to_owned(),
))
})?;
let url = url.to_string();
let url: Uri = url
.parse()
.map_err(|_| Error::GenericError(format!("Bad URL: {}", url)))?;
.map_err(|_| TorPostError::NotSent(Error::GenericError(format!("Bad URL: {}", url))))?;
let host = match url.host() {
None => return Err(Error::GenericError(format!("URL {} has bad host", url))),
None => {
return Err(TorPostError::NotSent(Error::GenericError(format!(
"URL {} has bad host",
url
))))
}
Some(h) => h,
}
.to_string();
let port = url.port_u16().unwrap_or(80);
let request = build_post_request(json, &url).map_err(TorPostError::NotSent)?;
let timeout = tor_config.request_timeout();
let (state_path, cache_path) = state_cache_paths(&tor_config);
let (client, _) = init_client(&state_path, &cache_path, tor_config)?;
let res: Result<String, Error> = thread::spawn(move || {
let (state_path, cache_path) = state_cache_paths(tor_config);
let (client, _) =
init_client(&state_path, &cache_path, tor_config).map_err(TorPostError::NotSent)?;
let res: Result<String, TorPostError> = thread::spawn(move || {
let c = client.clone();
client.runtime().block_on(async move {
let res = c
.runtime()
.timeout(timeout, async {
let stream = c
.connect((host, url.port_u16().unwrap_or(80)))
.await
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
let send_started = Arc::new(AtomicBool::new(false));
let send_started_in_request = send_started.clone();
let runtime = c.runtime().clone();
let res = runtime
.timeout(timeout, async move {
let stream = c.connect((host, port)).await.map_err(|e| {
TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))
})?;
let (mut request_sender, connection) =
hyper::client::conn::http1::handshake(TokioIo::new(stream))
.await
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
.map_err(|e| {
TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))
})?;
// Spawn a task to poll the connection and drive the HTTP state.
tokio::spawn(async move {
@@ -257,36 +306,44 @@ where
}
});
let resp = request_sender
.send_request(
Request::builder()
.uri(url)
.method("POST")
.body::<Full<Bytes>>(Full::from(json))
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?,
)
.await
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
send_started_in_request.store(true, Ordering::Release);
let resp = request_sender.send_request(request).await.map_err(|e| {
TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e)))
})?;
let body_resp = resp
.into_body()
.collect()
.await
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
let status = resp.status();
let body_resp = resp.into_body().collect().await.map_err(|e| {
TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e)))
})?;
let body = body_resp.to_bytes().into();
let body_text = String::from_utf8(body)
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
let body_text = String::from_utf8(body).map_err(|e| {
TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e)))
})?;
if !status.is_success() {
return Err(TorPostError::PossiblySent(Error::TorProcess(format!(
"HTTP request failed with status {}: {}",
status, body_text
))));
}
Ok(body_text)
})
.await;
match res {
Err(e) => Err(Error::TorProcess(format!("{:?}", e))),
Err(e) if send_started.load(Ordering::Acquire) => Err(TorPostError::PossiblySent(
Error::TorProcess(format!("{:?}", e)),
)),
Err(e) => Err(TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))),
Ok(body) => Ok(body),
}
})
})
.join()
.unwrap_or_else(|e| return Err(Error::TorProcess(format!("{:?}", e))))?;
.unwrap_or_else(|e| {
Err(TorPostError::PossiblySent(Error::TorProcess(format!(
"{:?}",
e
))))
})?;
res
}
@@ -296,8 +353,12 @@ fn init_client(
cache_path: &PathBuf,
tor_config: &TorConfig,
) -> Result<(Arc<TorClient<TokioNativeTlsRuntime>>, TorClientConfig), Error> {
let mut builder = TorClientConfigBuilder::from_directories(&state_path, cache_path);
let mut builder = TorClientConfigBuilder::from_directories(state_path, cache_path);
builder.address_filter().allow_onion_addrs(true);
// Circuit timeout minimum applies to listeners and sends too
builder
.override_net_params()
.insert("cbtmintimeout".into(), 60_000);
// Configure bridge.
if let Some(bridge_line) = tor_config.bridge.bridge_line.as_ref() {
@@ -345,7 +406,7 @@ fn init_client(
*cached_client_config = None;
}
}
let res = launch_client(config.clone(), &tor_config);
let res = launch_client(config.clone(), tor_config);
match res {
Ok(client) => {
cached_client_config.replace((client.clone(), config.clone()));
@@ -458,7 +519,7 @@ fn add_service_key(
Some(expanded_kp) => {
key_manager
.insert(
HsIdKey::from(expanded_kp.public().clone()),
HsIdKey::from(*expanded_kp.public()),
&HsIdPublicKeySpecifier::new(hs_nickname.clone()),
KeystoreSelector::Primary,
true,
@@ -476,3 +537,21 @@ fn add_service_key(
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::build_post_request;
use hyper::{Method, Uri};
#[test]
fn builds_origin_form_json_request() {
let url: Uri = "http://example.onion:8080/v1?test=1".parse().unwrap();
let request = build_post_request("{}".to_string(), &url).unwrap();
assert_eq!(request.method(), Method::POST);
assert_eq!(request.uri(), "/v1?test=1");
assert_eq!(request.headers()["host"], "example.onion:8080");
assert_eq!(request.headers()["accept"], "application/json");
assert_eq!(request.headers()["content-type"], "application/json");
}
}
+29 -66
View File
@@ -87,8 +87,8 @@ impl<'a> FlagParser<'a> {
fn end(&mut self, is_bool_flag: bool, right: &str) -> usize {
if is_bool_flag {
0
} else if right.starts_with('"') {
right[1..].find('"').unwrap_or(0) + 2
} else if let Some(stripped) = right.strip_prefix('"') {
stripped.find('"').unwrap_or(0) + 2
} else {
right.find(' ').unwrap_or(right.len())
}
@@ -113,7 +113,7 @@ impl<'a> Iterator for FlagParser<'a> {
let end = self.end(self.is_bool_flag, right);
let key = left.split_whitespace().last()?;
let val = &right[..end];
self.line = &right[end..].trim();
self.line = right[end..].trim();
Some((key, val))
}
}
@@ -121,7 +121,7 @@ impl<'a> Iterator for FlagParser<'a> {
/// Every args field that could be in the bridge line
/// obfs4 args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/obfs4/obfs4.go#L86-L91
/// meek_lite args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/meeklite/meek.go#L93-L127
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct Transport {
/// transport type: obfs4, meek_lite, meek, snowflake
pub transport: Option<String>,
@@ -143,22 +143,6 @@ pub struct Transport {
pub disablehpkp: Option<String>,
}
impl Default for Transport {
fn default() -> Transport {
Transport {
transport: None,
server: None,
fingerprint: None,
cert: None,
iatmode: None,
url: None,
front: None,
utls: None,
disablehpkp: None,
}
}
}
impl Transport {
/// Parse the server address of the bridge line
fn parse_socketaddr_arg(arg: Option<&&str>) -> Result<String, Error> {
@@ -170,7 +154,7 @@ impl Transport {
Ok(address.to_string())
}
None => {
let msg = format!("Missing bridge server address");
let msg = "Missing bridge server address".to_string();
Err(Error::TorBridge(msg))
}
}
@@ -202,7 +186,7 @@ impl Transport {
})?;
if cert_vec.len() != 52 {
let msg = format!("Invalid certificate: {}", arg);
return Err(Error::TorBridge(msg).into());
return Err(Error::TorBridge(msg));
}
Ok(arg.to_string())
}
@@ -219,16 +203,17 @@ impl Transport {
/// Parse the max value for the arg -max in the client line option (snowflake)
fn parse_hpkp_arg(arg: &str) -> Result<String, Error> {
let max = arg.parse::<bool>().map_err(|_e| {
Error::TorBridge(
format!("Invalid -max value: {}, must be \"true\" or \"false\"", arg).into(),
)
Error::TorBridge(format!(
"Invalid -max value: {}, must be \"true\" or \"false\"",
arg
))
})?;
Ok(max.to_string())
}
}
// Client Plugin such as snowflake or obfs4proxy
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct PluginClient {
// Path plugin client
pub path: Option<String>,
@@ -236,15 +221,6 @@ pub struct PluginClient {
pub option: Option<String>,
}
impl Default for PluginClient {
fn default() -> PluginClient {
PluginClient {
path: None,
option: None,
}
}
}
impl PluginClient {
/// Get the hashmap key(argument) and attached value of the client option line.
pub fn get_flags(s: &str) -> HashMap<&str, &str> {
@@ -333,7 +309,7 @@ impl PluginClient {
"Invalid ICE address: {}. Must be a stun or turn address",
addr
);
return Err(Error::TorBridge(msg).into());
return Err(Error::TorBridge(msg));
}
}
Ok(ice_addr.to_string())
@@ -372,9 +348,9 @@ impl PluginClient {
let (ck_url, ck_ice) = (hm_flags.contains_key("-url"), hm_flags.contains_key("-ice"));
if !(ck_url || ck_ice) {
let msg = if !ck_url {
format!("Missing URL argurment for snowflake transport, specify \"-url\"")
"Missing URL argurment for snowflake transport, specify \"-url\"".to_string()
} else {
format!("Missing ICE argurment for snowflake transport, specify \"-ice\"")
"Missing ICE argurment for snowflake transport, specify \"-ice\"".to_string()
};
return Err(Error::TorBridge(msg));
}
@@ -410,7 +386,7 @@ impl PluginClient {
}
/// Tor Bridge Field
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct TorBridge {
/// tor bridge (transport field)
pub bridge: Transport,
@@ -418,15 +394,6 @@ pub struct TorBridge {
pub client: PluginClient,
}
impl Default for TorBridge {
fn default() -> TorBridge {
TorBridge {
bridge: Transport::default(),
client: PluginClient::default(),
}
}
}
impl TorBridge {
/// Get the hashmap key(argument) and attached value of the bridge line. r
pub fn get_flags(s: &str) -> HashMap<&str, &str> {
@@ -541,8 +508,8 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
let cert = match flags.get_key_value("cert=") {
Some(hm) => Transport::parse_cert_arg(hm.1)?,
None => {
let msg =
format!("Missing cert argurment in obfs4 transport, specify \"cert=\"");
let msg = "Missing cert argurment in obfs4 transport, specify \"cert=\""
.to_string();
return Err(Error::TorBridge(msg));
}
};
@@ -559,14 +526,14 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
bridge: Transport {
transport: Some("obfs4".into()),
server: Some(socketaddr.to_string()),
fingerprint: fingerprint,
cert: Some(cert.into()),
fingerprint,
cert: Some(cert),
iatmode: Some(iatmode),
..Transport::default()
},
client: PluginClient {
path: Some(path),
option: option,
option,
},
};
Ok(tbpc)
@@ -578,9 +545,8 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
let url = match flags.get_key_value("url=") {
Some(hm) => PluginClient::parse_url_arg(hm.1)?,
None => {
let msg = format!(
"Missing url argurment in meek_lite transport, specify \"url=\""
);
let msg = "Missing url argurment in meek_lite transport, specify \"url=\""
.to_string();
return Err(Error::TorBridge(msg));
}
};
@@ -588,10 +554,7 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
Some(hm) => Some(PluginClient::parse_front_arg(hm.1)?),
None => None,
};
let utls = match flags.get_key_value("utls=") {
Some(hm) => Some(hm.1.to_string()),
None => None,
};
let utls = flags.get_key_value("utls=").map(|hm| hm.1.to_string());
let disablehpkp = match flags.get_key_value("disablehpkp=") {
Some(hm) => Some(Transport::parse_hpkp_arg(hm.1)?),
None => None,
@@ -605,16 +568,16 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
bridge: Transport {
transport: Some("meek_lite".into()),
server: Some(socketaddr.to_string()),
fingerprint: fingerprint,
fingerprint,
url: Some(url),
front: front,
utls: utls,
disablehpkp: disablehpkp,
front,
utls,
disablehpkp,
..Transport::default()
},
client: PluginClient {
path: Some(path),
option: option,
option,
},
};
Ok(tbpc)
@@ -638,7 +601,7 @@ impl TryFrom<TorBridgeConfig> for TorBridge {
bridge: Transport {
transport: Some("snowflake".into()),
server: Some(socketaddr.to_string()),
fingerprint: fingerprint,
fingerprint,
..Transport::default()
},
client: PluginClient {
+4 -4
View File
@@ -131,7 +131,7 @@ pub fn create_onion_service_pub_key_file(
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())
file.write_all(format!("{}.onion\n", hostname).as_bytes())
.map_err(|_| Error::IO)?;
Ok(())
}
@@ -228,7 +228,7 @@ pub fn output_tor_listener_config(
let mut service_dirs = vec![];
for k in listener_keys {
let service_dir = output_onion_service_config(tor_config_directory, &k)?;
let service_dir = output_onion_service_config(tor_config_directory, k)?;
service_dirs.push(service_dir.to_string());
}
@@ -253,7 +253,7 @@ pub fn output_tor_sender_config(
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)?;
fs::create_dir_all(tor_config_dir).map_err(|_| Error::IO)?;
output_torrc(
tor_config_dir,
@@ -272,7 +272,7 @@ pub fn is_tor_address(input: &str) -> Result<(), Error> {
Ok(_) => Ok(()),
Err(e) => {
let msg = format!("{:?}", e);
Err(Error::NotOnion(msg).into())
Err(Error::NotOnion(msg))
}
}
}
+8 -2
View File
@@ -90,6 +90,12 @@ pub struct TorProcess {
sys: System,
}
impl Default for TorProcess {
fn default() -> Self {
Self::new()
}
}
impl TorProcess {
pub fn new() -> Self {
TorProcess {
@@ -153,7 +159,7 @@ impl TorProcess {
let mut tor = Command::new(&self.tor_cmd);
if let Some(ref d) = self.working_dir {
tor.current_dir(&d);
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() {
@@ -167,7 +173,7 @@ impl TorProcess {
}
}
if let Some(ref torrc_path) = self.torrc_path {
tor.args(&vec!["-f", torrc_path]);
tor.args(vec!["-f", torrc_path]);
}
let mut tor_process = tor
.args(&self.args)
+7 -22
View File
@@ -20,7 +20,7 @@ use std::str;
use url::Host;
/// Tor Proxy
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct TorProxy {
/// proxy type used for the proxy, eg "socks4", "socks5", "http", "https"
pub transport: Option<String>,
@@ -34,18 +34,6 @@ pub struct TorProxy {
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;
@@ -70,7 +58,7 @@ impl TorProxy {
}
pub fn parse_address(addr: &str) -> Result<(String, Option<u16>), Error> {
let (host, str_port) = TorProxy::parse_host_port(&addr)?;
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 {
@@ -92,13 +80,10 @@ impl TorProxy {
for port in ports.clone() {
allowed_ports.push_str(format!("*:{}", port).as_str());
if port != last_port {
allowed_ports.push_str(",");
allowed_ports.push(',');
}
}
hm.insert(
"ReachableAddresses".to_string(),
format!("{}", allowed_ports.clone()),
);
hm.insert("ReachableAddresses".to_string(), allowed_ports);
}
let transport = match self.transport {
@@ -156,7 +141,7 @@ impl TryFrom<TorProxyConfig> for TorProxy {
address_addr = host
}
Ok(TorProxy {
transport: Some(transport.into()),
transport: Some(transport),
address: Some(address_addr),
username: tb.username,
password: tb.password,
@@ -167,7 +152,7 @@ impl TryFrom<TorProxyConfig> for TorProxy {
"Missing proxy address: {} - must be <IP:PORT> or <Hostname>",
transport
);
return Err(Error::TorProxy(msg).into());
Err(Error::TorProxy(msg))
}
}
// Missing transport type
@@ -176,7 +161,7 @@ impl TryFrom<TorProxyConfig> for TorProxy {
"Invalid proxy transport: {} - must be socks4/socks5/http(s)",
transport
);
Err(Error::TorProxy(msg).into())
Err(Error::TorProxy(msg))
}
}
} else {