Skip to content

Commit bf93432

Browse files
committed
rust: use agent for http requests
Also update ureq to latest 1.x; update to 2.x requires to bump MSRV from 1.42.
1 parent 476fca1 commit bf93432

File tree

5 files changed

+45
-22
lines changed

5 files changed

+45
-22
lines changed

subprojects/gdk_rust/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ chrono = "0.4.11"
2525
log = "0.4.8"
2626
android_logger = { version = "0.8.6", optional = true }
2727
url = "1.7.2"
28-
ureq = { version = "1.0.0", features = ["json"] }
28+
ureq = { version = "1.5.5", features = ["json", "socks-proxy"] }
2929

3030
[dev-dependencies]
3131
tempdir = "0.3.7"

subprojects/gdk_rust/gdk_electrum/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ libc = "0.2"
2121
android_logger = { version = "0.8.6", optional = true }
2222
electrum-client = "0.7.0"
2323
chrono = "0.4.11"
24-
ureq = { version = "1.0.0", features = ["json"] }
24+
ureq = { version = "1.5.5", features = ["json", "socks-proxy"] }
2525
block-modes = "0.3.3"
2626
aes = "0.3.2"
2727
tempdir = "0.3.7"

subprojects/gdk_rust/gdk_electrum/src/lib.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,10 @@ impl ElectrumSession {
212212
self.wallet.as_mut().ok_or_else(|| Error::Generic("wallet not initialized".into()))?;
213213
Ok(wallet.write().unwrap())
214214
}
215+
216+
pub fn build_request_agent(&self) -> ureq::Agent {
217+
ureq::Agent::new().build()
218+
}
215219
}
216220

217221
fn try_get_fee_estimates(client: &Client) -> Result<Vec<FeeEstimate>, Error> {
@@ -319,7 +323,8 @@ impl Session<Error> for ElectrumSession {
319323
pin: String,
320324
details: PinGetDetails,
321325
) -> Result<Vec<Notification>, Error> {
322-
let manager = PinManager::new()?;
326+
let agent = self.build_request_agent();
327+
let manager = PinManager::new(agent)?;
323328
let client_key = SecretKey::from_slice(&hex::decode(&details.pin_identifier)?)?;
324329
let server_key = manager.get_pin(pin.as_bytes(), &client_key)?;
325330
let iv = hex::decode(&details.salt)?;
@@ -622,7 +627,8 @@ impl Session<Error> for ElectrumSession {
622627
}
623628

624629
fn set_pin(&self, details: &PinSetDetails) -> Result<PinGetDetails, Error> {
625-
let manager = PinManager::new()?;
630+
let agent = self.build_request_agent();
631+
let manager = PinManager::new(agent)?;
626632
let client_key = SecretKey::new(&mut thread_rng());
627633
let server_key = manager.set_pin(details.pin.as_bytes(), &client_key)?;
628634
let iv = thread_rng().gen::<[u8; 16]>();
@@ -794,8 +800,9 @@ impl Session<Error> for ElectrumSession {
794800
let last_modified =
795801
self.get_wallet()?.store.read()?.cache.assets_last_modified.clone();
796802
let base_url = self.network.registry_base_url()?;
803+
let agent = self.build_request_agent();
797804
thread::spawn(move || {
798-
match call_assets(base_url, registry_policy, last_modified) {
805+
match call_assets(agent, base_url, registry_policy, last_modified) {
799806
Ok(p) => tx_assets.send(Some(p)),
800807
Err(_) => tx_assets.send(None),
801808
}
@@ -807,7 +814,8 @@ impl Session<Error> for ElectrumSession {
807814
let last_modified =
808815
self.get_wallet()?.store.read()?.cache.icons_last_modified.clone();
809816
let base_url = self.network.registry_base_url()?;
810-
thread::spawn(move || match call_icons(base_url, last_modified) {
817+
let agent = self.build_request_agent();
818+
thread::spawn(move || match call_icons(agent, base_url, last_modified) {
811819
Ok(p) => tx_icons.send(Some(p)),
812820
Err(_) => tx_icons.send(None),
813821
});
@@ -907,11 +915,16 @@ impl ElectrumSession {
907915
}
908916
}
909917

910-
fn call_icons(base_url: String, last_modified: String) -> Result<(Value, String), Error> {
918+
fn call_icons(
919+
agent: ureq::Agent,
920+
base_url: String,
921+
last_modified: String,
922+
) -> Result<(Value, String), Error> {
911923
// TODO gzip encoding
912924
let url = format!("{}/{}", base_url, "icons.json");
913925
info!("START call_icons {}", &url);
914-
let icons_response = ureq::get(&url)
926+
let icons_response = agent
927+
.get(&url)
915928
.timeout_connect(15_000)
916929
.timeout_read(15_000)
917930
.set("If-Modified-Since", &last_modified)
@@ -925,14 +938,16 @@ fn call_icons(base_url: String, last_modified: String) -> Result<(Value, String)
925938
}
926939

927940
fn call_assets(
941+
agent: ureq::Agent,
928942
base_url: String,
929943
registry_policy: String,
930944
last_modified: String,
931945
) -> Result<(Value, String), Error> {
932946
// TODO add gzip encoding
933947
let url = format!("{}/{}", base_url, "index.json");
934948
info!("START call_assets {}", &url);
935-
let assets_response = ureq::get(&url)
949+
let assets_response = agent
950+
.get(&url)
936951
.timeout_connect(15_000)
937952
.timeout_read(15_000)
938953
.set("If-Modified-Since", &last_modified)

subprojects/gdk_rust/gdk_electrum/src/pin/mod.rs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ pub struct PinManager {
5050
response_encryption_key: ShaHmac,
5151
response_hmac_key: ShaHmac,
5252
rng: ThreadRng,
53+
agent: ureq::Agent,
5354
}
5455

5556
enum PinOp {
@@ -58,10 +59,10 @@ enum PinOp {
5859
}
5960

6061
impl PinManager {
61-
pub fn new() -> Result<Self, Error> {
62+
pub fn new(agent: ureq::Agent) -> Result<Self, Error> {
6263
info!("PinManager new()");
63-
let data = Self::handshake_request()?;
64-
Self::with_handshake(data)
64+
let data = Self::handshake_request(&agent)?;
65+
Self::with_handshake(data, agent)
6566
}
6667

6768
/// `set_pin` consume self, because handshake must be done for every request
@@ -74,8 +75,9 @@ impl PinManager {
7475
self.server_call(pin_secret, private_key, PinOp::Get).map_err(|_| Error::PinError)
7576
}
7677

77-
fn handshake_request() -> Result<Handshake, Error> {
78-
let response = ureq::post(&format!("{}/start_handshake", PINSERVER_URL))
78+
fn handshake_request(agent: &ureq::Agent) -> Result<Handshake, Error> {
79+
let response = agent
80+
.post(&format!("{}/start_handshake", PINSERVER_URL))
7981
.set("content-length", "0")
8082
.call();
8183
if !response.ok() {
@@ -85,7 +87,7 @@ impl PinManager {
8587
Ok(data)
8688
}
8789

88-
fn with_handshake(data: Handshake) -> Result<Self, Error> {
90+
fn with_handshake(data: Handshake, agent: ureq::Agent) -> Result<Self, Error> {
8991
let mut rng = rand::thread_rng();
9092
let pinserver_pubkey = PublicKey::from_str(PINSERVER_PUBKEY).unwrap();
9193

@@ -109,6 +111,7 @@ impl PinManager {
109111
request_hmac_key: Self::derive(1, &shared_secret),
110112
response_encryption_key: Self::derive(2, &shared_secret),
111113
response_hmac_key: Self::derive(3, &shared_secret),
114+
agent,
112115
})
113116
}
114117

@@ -165,7 +168,9 @@ impl PinManager {
165168
hmac_encrypted_data: hex::encode(&hmac[..]),
166169
};
167170

168-
let response = ureq::post(&format!("{}/{}", PINSERVER_URL, op))
171+
let response = self
172+
.agent
173+
.post(&format!("{}/{}", PINSERVER_URL, op))
169174
.send_json(serde_json::to_value(&req).unwrap());
170175

171176
if !response.ok() {
@@ -235,10 +240,10 @@ mod test {
235240
let mut rng = rand::thread_rng();
236241
let secret_key = SecretKey::new(&mut rng);
237242

238-
let manager = PinManager::new().unwrap();
243+
let manager = PinManager::new(ureq::Agent::new()).unwrap();
239244
let pin_key_set = manager.set_pin(&[0u8; 4], &secret_key).unwrap();
240245

241-
let manager = PinManager::new().unwrap();
246+
let manager = PinManager::new(ureq::Agent::new()).unwrap();
242247
let pin_key_get = manager.get_pin(&[0u8; 4], &secret_key).unwrap();
243248
assert_eq!(pin_key_get, pin_key_set);
244249
}
@@ -247,7 +252,7 @@ mod test {
247252
fn test_handshake() {
248253
// test vector taken from a random response from the production pin server
249254
let data = Handshake { sig: "004a58b09b6b4b6585536c5fbd662fb729a277426875a644fa56f5d05d6724281576f9d7844fc131102cd9d4fd56ca0b7f3cf9872379510407b3075f5c862c70".to_string(), ske: "032541c31f808a28750daf386e52ad70f16db153fa9e8375a6178021a0c7a74c09".to_string() };
250-
assert!(PinManager::with_handshake(data).is_ok());
255+
assert!(PinManager::with_handshake(data, ureq::Agent::new()).is_ok());
251256
}
252257

253258
#[test]

subprojects/gdk_rust/src/lib.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,10 @@ fn fetch_cached_exchange_rates(sess: &mut GdkSession) -> Option<Vec<Ticker>> {
232232
debug!("hit exchange rate cache");
233233
} else {
234234
info!("missed exchange rate cache");
235-
let rates = fetch_exchange_rates();
235+
let agent = match sess.backend {
236+
GdkBackend::Electrum(ref s) => s.build_request_agent(),
237+
};
238+
let rates = fetch_exchange_rates(agent);
236239
// still record time even if we get no results
237240
sess.last_xr_fetch = SystemTime::now();
238241
if !rates.is_empty() {
@@ -319,9 +322,9 @@ pub extern "C" fn GDKRUST_set_notification_handler(
319322
GA_OK
320323
}
321324

322-
fn fetch_exchange_rates() -> Vec<Ticker> {
325+
fn fetch_exchange_rates(agent: ureq::Agent) -> Vec<Ticker> {
323326
if let Ok(result) =
324-
ureq::get("https://api-pub.bitfinex.com/v2/tickers?symbols=tBTCUSD").call().into_json()
327+
agent.get("https://api-pub.bitfinex.com/v2/tickers?symbols=tBTCUSD").call().into_json()
325328
{
326329
if let Value::Array(array) = result {
327330
if let Some(Value::Array(array)) = array.get(0) {

0 commit comments

Comments
 (0)