Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ edition = "2021"
name = "electrum_client"
path = "src/lib.rs"

[[example]]
name = "tofu"
required-features = ["tofu"]

[dependencies]
log = "^0.4"
bitcoin = { version = "0.32", features = ["serde"] }
Expand All @@ -43,6 +47,7 @@ proxy = ["byteorder", "winapi", "libc"]
rustls = ["webpki-roots", "dep:rustls", "rustls/default"]
rustls-ring = ["webpki-roots", "dep:rustls", "rustls/ring", "rustls/logging", "rustls/std", "rustls/tls12"]
openssl = ["dep:openssl"]
tofu = []

# Old feature names
use-rustls = ["rustls"]
Expand Down
36 changes: 36 additions & 0 deletions examples/tofu.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// cargo run --example tofu --features tofu
extern crate electrum_client;

use electrum_client::{Client, Config, ElectrumApi, TofuStore};
use std::collections::HashMap;
use std::io;
use std::sync::{Arc, Mutex};

#[derive(Debug, Default)]
struct InMemoryTofuStore {
certs: Mutex<HashMap<String, Vec<u8>>>,
}

impl TofuStore for InMemoryTofuStore {
fn get_certificate(&self, host: &str) -> io::Result<Option<Vec<u8>>> {
Ok(self.certs.lock().unwrap().get(host).cloned())
}

fn set_certificate(&self, host: &str, cert: Vec<u8>) -> io::Result<()> {
self.certs.lock().unwrap().insert(host.to_string(), cert);
Ok(())
}
}

fn main() {
let store = Arc::new(InMemoryTofuStore::default());

let client = Client::from_config_with_tofu(
"ssl://electrum.blockstream.info:50002",
Config::default(),
store,
)
.unwrap();

println!("{:#?}", client.server_features());
}
100 changes: 99 additions & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Electrum Client

#[cfg(feature = "tofu")]
use std::sync::Arc;
use std::{borrow::Borrow, sync::RwLock};

use log::{info, warn};
Expand All @@ -10,6 +12,8 @@ use crate::api::ElectrumApi;
use crate::batch::Batch;
use crate::config::Config;
use crate::raw_client::*;
#[cfg(feature = "tofu")]
use crate::tofu::TofuStore;
use crate::types::*;
use std::convert::TryFrom;

Expand All @@ -35,6 +39,8 @@ pub struct Client {
client_type: RwLock<ClientType>,
config: Config,
url: String,
#[cfg(feature = "tofu")]
tofu_store: Option<Arc<dyn TofuStore>>,
}

macro_rules! impl_inner_call {
Expand Down Expand Up @@ -74,7 +80,7 @@ macro_rules! impl_inner_call {
if let Ok(mut write_client) = $self.client_type.try_write() {
loop {
std::thread::sleep(std::time::Duration::from_secs((1 << errors.len()).min(30) as u64));
match ClientType::from_config(&$self.url, &$self.config) {
match $self.client_type_adapter() {
Ok(new_client) => {
info!("Succesfully created new client");
*write_client = new_client;
Expand Down Expand Up @@ -179,6 +185,61 @@ impl ClientType {
Ok(client)
}
}

/// Constructor that supports multiple backends and allows configuration through
/// the Config, enabling TOFU certificate checks for SSL connections
#[cfg(feature = "tofu")]
pub fn from_config_with_tofu(
url: &str,
config: &Config,
tofu_store: Arc<dyn TofuStore>,
) -> Result<Self, Error> {
let auth_provider = config.authorization_provider().cloned();

#[cfg(any(feature = "openssl", feature = "rustls", feature = "rustls-ring"))]
if url.starts_with("ssl://") {
let url = url.replacen("ssl://", "", 1);
#[cfg(feature = "proxy")]
let raw_client = match config.socks5() {
Some(socks5) => RawClient::new_proxy_ssl_with_tofu(
url.as_str(),
config.validate_domain(),
socks5,
config.timeout(),
tofu_store,
auth_provider,
)?,
None => RawClient::new_ssl_with_tofu(
url.as_str(),
config.validate_domain(),
config.timeout(),
tofu_store,
auth_provider,
)?,
};
#[cfg(not(feature = "proxy"))]
let raw_client = RawClient::new_ssl_with_tofu(
url.as_str(),
config.validate_domain(),
config.timeout(),
tofu_store,
auth_provider,
)?;

return Ok(ClientType::SSL(raw_client));
}

#[cfg(not(any(feature = "openssl", feature = "rustls", feature = "rustls-ring")))]
if url.starts_with("ssl://") {
return Err(Error::Message(
"SSL connections require one of the following features to be enabled: openssl, rustls, or rustls-ring".to_string()
));
}

Err(Error::Message(
"TOFU validation is available only for SSL connections".to_string(),
))
}
}

impl Client {
Expand All @@ -204,8 +265,45 @@ impl Client {
client_type,
config,
url: url.to_string(),
#[cfg(feature = "tofu")]
tofu_store: None,
})
}

/// Creates a new client with TOFU (Trust On First Use) certificate validation.
/// This constructor requires an SSL URL and stores/verifies server
/// certificates using the provided store
#[cfg(feature = "tofu")]
pub fn from_config_with_tofu(
url: &str,
config: Config,
tofu_store: Arc<dyn TofuStore>,
) -> Result<Self, Error> {
let client_type = RwLock::new(ClientType::from_config_with_tofu(
url,
&config,
tofu_store.clone(),
)?);
Comment thread
lucasdbr05 marked this conversation as resolved.

Ok(Client {
client_type,
config,
url: url.to_string(),
tofu_store: Some(tofu_store),
})
}

// Recreate the client using the same strategy as the original constructor
fn client_type_adapter(&self) -> Result<ClientType, Error> {
#[cfg(feature = "tofu")]
{
if let Some(store) = self.tofu_store.as_ref() {
return ClientType::from_config_with_tofu(&self.url, &self.config, store.clone());
}
}

ClientType::from_config(&self.url, &self.config)
}
}

impl ElectrumApi for Client {
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,15 @@ mod config;

pub mod raw_client;
mod stream;
#[cfg(feature = "tofu")]
mod tofu;
mod types;
pub mod utils;

pub use api::ElectrumApi;
pub use batch::Batch;
pub use client::*;
pub use config::{AuthProvider, Config, ConfigBuilder, Socks5Config};
#[cfg(feature = "tofu")]
pub use tofu::TofuStore;
pub use types::*;
Loading
Loading