Skip to content

Commit 434f439

Browse files
committed
rust: read proxy and use it for ureq requests
1 parent bf93432 commit 434f439

File tree

5 files changed

+71
-19
lines changed

5 files changed

+71
-19
lines changed

subprojects/gdk_rust/gdk_electrum/src/error.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,9 @@ impl From<aead::Error> for Error {
230230
Error::Generic(err.to_string())
231231
}
232232
}
233+
234+
impl From<ureq::Error> for Error {
235+
fn from(err: ureq::Error) -> Self {
236+
Error::Generic(err.to_string())
237+
}
238+
}

subprojects/gdk_rust/gdk_electrum/src/lib.rs

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ impl Closer {
112112

113113
pub struct ElectrumSession {
114114
pub data_root: String,
115+
pub proxy: Option<String>,
115116
pub network: Network,
116117
pub url: ElectrumUrl,
117118
pub wallet: Option<Arc<RwLock<WalletCtx>>>,
@@ -179,16 +180,43 @@ pub fn determine_electrum_url_from_net(network: &Network) -> Result<ElectrumUrl,
179180
determine_electrum_url(&network.electrum_url, network.tls, network.validate_domain)
180181
}
181182

183+
fn socksify(proxy: Option<&str>) -> Option<String> {
184+
const SOCKS5: &str = "socks5://";
185+
if let Some(proxy) = proxy {
186+
let trimmed = proxy.trim();
187+
if trimmed.is_empty() {
188+
None
189+
} else if trimmed.starts_with(SOCKS5) {
190+
Some(trimmed.to_string())
191+
} else {
192+
Some(format!("{}{}", SOCKS5, trimmed))
193+
}
194+
} else {
195+
None
196+
}
197+
}
198+
182199
impl ElectrumSession {
183-
pub fn new_session(network: Network, db_root: &str, url: ElectrumUrl) -> Result<Self, Error> {
184-
Ok(Self::create_session(network, db_root, url))
200+
pub fn new_session(
201+
network: Network,
202+
db_root: &str,
203+
proxy: Option<&str>,
204+
url: ElectrumUrl,
205+
) -> Result<Self, Error> {
206+
Ok(Self::create_session(network, db_root, proxy, url))
185207
}
186208
}
187209

188210
impl ElectrumSession {
189-
pub fn create_session(network: Network, db_root: &str, url: ElectrumUrl) -> Self {
211+
pub fn create_session(
212+
network: Network,
213+
db_root: &str,
214+
proxy: Option<&str>,
215+
url: ElectrumUrl,
216+
) -> Self {
190217
Self {
191218
data_root: db_root.to_string(),
219+
proxy: socksify(proxy),
192220
network,
193221
url,
194222
wallet: None,
@@ -213,8 +241,16 @@ impl ElectrumSession {
213241
Ok(wallet.write().unwrap())
214242
}
215243

216-
pub fn build_request_agent(&self) -> ureq::Agent {
217-
ureq::Agent::new().build()
244+
pub fn build_request_agent(&self) -> Result<ureq::Agent, Error> {
245+
match &self.proxy {
246+
Some(proxy) => {
247+
let proxy = ureq::Proxy::new(&proxy)?;
248+
let mut agent = ureq::agent();
249+
agent.set_proxy(proxy);
250+
Ok(agent)
251+
}
252+
None => Ok(ureq::agent()),
253+
}
218254
}
219255
}
220256

@@ -296,6 +332,11 @@ impl Session<Error> for ElectrumSession {
296332
info!("setting db_root to {:?}", self.data_root);
297333
}
298334

335+
if self.proxy.is_none() {
336+
self.proxy = socksify(net_params["proxy"].as_str());
337+
info!("setting proxy to {:?}", self.proxy);
338+
}
339+
299340
let mnemonic = match self.get_mnemonic() {
300341
Ok(mnemonic) => Some(mnemonic.clone()),
301342
Err(_) => None,
@@ -323,7 +364,7 @@ impl Session<Error> for ElectrumSession {
323364
pin: String,
324365
details: PinGetDetails,
325366
) -> Result<Vec<Notification>, Error> {
326-
let agent = self.build_request_agent();
367+
let agent = self.build_request_agent()?;
327368
let manager = PinManager::new(agent)?;
328369
let client_key = SecretKey::from_slice(&hex::decode(&details.pin_identifier)?)?;
329370
let server_key = manager.get_pin(pin.as_bytes(), &client_key)?;
@@ -627,7 +668,7 @@ impl Session<Error> for ElectrumSession {
627668
}
628669

629670
fn set_pin(&self, details: &PinSetDetails) -> Result<PinGetDetails, Error> {
630-
let agent = self.build_request_agent();
671+
let agent = self.build_request_agent()?;
631672
let manager = PinManager::new(agent)?;
632673
let client_key = SecretKey::new(&mut thread_rng());
633674
let server_key = manager.set_pin(details.pin.as_bytes(), &client_key)?;
@@ -800,7 +841,7 @@ impl Session<Error> for ElectrumSession {
800841
let last_modified =
801842
self.get_wallet()?.store.read()?.cache.assets_last_modified.clone();
802843
let base_url = self.network.registry_base_url()?;
803-
let agent = self.build_request_agent();
844+
let agent = self.build_request_agent()?;
804845
thread::spawn(move || {
805846
match call_assets(agent, base_url, registry_policy, last_modified) {
806847
Ok(p) => tx_assets.send(Some(p)),
@@ -814,7 +855,7 @@ impl Session<Error> for ElectrumSession {
814855
let last_modified =
815856
self.get_wallet()?.store.read()?.cache.icons_last_modified.clone();
816857
let base_url = self.network.registry_base_url()?;
817-
let agent = self.build_request_agent();
858+
let agent = self.build_request_agent()?;
818859
thread::spawn(move || match call_icons(agent, base_url, last_modified) {
819860
Ok(p) => tx_icons.send(Some(p)),
820861
Err(_) => tx_icons.send(None),

subprojects/gdk_rust/src/lib.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -201,15 +201,16 @@ fn create_session(network: &Value) -> Result<GdkSession, Value> {
201201
let parsed_network = parsed_network.unwrap();
202202

203203
let db_root = network["db_root"].as_str().unwrap_or("");
204+
let proxy = network["proxy"].as_str();
204205

205206
match network["server_type"].as_str() {
206207
// Some("rpc") => GDKRUST_session::Rpc( GDKRPC_session::create_session(parsed_network.unwrap()).unwrap() ),
207208
Some("electrum") => {
208209
let url = gdk_electrum::determine_electrum_url_from_net(&parsed_network)
209210
.map_err(|x| json!(x))?;
210211

211-
let session =
212-
ElectrumSession::new_session(parsed_network, db_root, url).map_err(|x| json!(x))?;
212+
let session = ElectrumSession::new_session(parsed_network, db_root, proxy, url)
213+
.map_err(|x| json!(x))?;
213214
let backend = GdkBackend::Electrum(session);
214215

215216
// some time in the past
@@ -235,12 +236,14 @@ fn fetch_cached_exchange_rates(sess: &mut GdkSession) -> Option<Vec<Ticker>> {
235236
let agent = match sess.backend {
236237
GdkBackend::Electrum(ref s) => s.build_request_agent(),
237238
};
238-
let rates = fetch_exchange_rates(agent);
239-
// still record time even if we get no results
240-
sess.last_xr_fetch = SystemTime::now();
241-
if !rates.is_empty() {
242-
// only set last_xr if we got new non-empty rates
243-
sess.last_xr = Some(rates);
239+
if let Ok(agent) = agent {
240+
let rates = fetch_exchange_rates(agent);
241+
// still record time even if we get no results
242+
sess.last_xr_fetch = SystemTime::now();
243+
if !rates.is_empty() {
244+
// only set last_xr if we got new non-empty rates
245+
sess.last_xr = Some(rates);
246+
}
244247
}
245248
}
246249

subprojects/gdk_rust/tests/integration.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,8 @@ fn subaccounts() {
278278
let url = determine_electrum_url_from_net(&network).unwrap();
279279
let db_root_dir = TempDir::new("electrum_integration_tests").unwrap();
280280
let db_root = format!("{}", db_root_dir.path().display());
281-
ElectrumSession::create_session(network, &db_root, url)
281+
let proxy = Some("");
282+
ElectrumSession::create_session(network, &db_root, proxy, url)
282283
};
283284
let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string().into();
284285
new_session.login(&mnemonic, None).unwrap();

subprojects/gdk_rust/tests/test_session.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,11 @@ pub fn setup(
217217
let db_root_dir = TempDir::new("electrum_integration_tests").unwrap();
218218

219219
let db_root = format!("{}", db_root_dir.path().display());
220+
let proxy = Some("");
220221
let url = determine_electrum_url_from_net(&network).unwrap();
221222

222223
info!("creating gdk session");
223-
let mut session = ElectrumSession::create_session(network.clone(), &db_root, url);
224+
let mut session = ElectrumSession::create_session(network.clone(), &db_root, proxy, url);
224225

225226
let mnemonic: Mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string().into();
226227
info!("logging in gdk session");

0 commit comments

Comments
 (0)