Skip to content

Commit 88e92af

Browse files
committed
Getting rid of lock().unwrap()
1 parent e3aa6a5 commit 88e92af

File tree

3 files changed

+34
-33
lines changed

3 files changed

+34
-33
lines changed

src/raw_client.rs

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -452,13 +452,7 @@ impl<S: Read + Write> RawClient<S> {
452452
// might have already received a response for that id, but we don't know it
453453
// yet. Exiting here forces the calling code to fallback to the sender-receiver
454454
// method, and it should find a message there waiting for it.
455-
if self
456-
.waiting_map
457-
.lock()
458-
.unwrap()
459-
.get(&until_message)
460-
.is_none()
461-
{
455+
if self.waiting_map.lock()?.get(&until_message).is_none() {
462456
return Err(Error::CouldntLockReader);
463457
}
464458
}
@@ -494,7 +488,7 @@ impl<S: Read + Write> RawClient<S> {
494488
);
495489

496490
// Remove ourselves from the "waiting map"
497-
let mut map = self.waiting_map.lock().unwrap();
491+
let mut map = self.waiting_map.lock()?;
498492
map.remove(&resp_id);
499493

500494
// If the map is not empty, we select a random thread to become the
@@ -512,8 +506,7 @@ impl<S: Read + Write> RawClient<S> {
512506
// move on
513507
trace!("Reader thread received response for {}", resp_id);
514508

515-
if let Some(sender) = self.waiting_map.lock().unwrap().remove(&resp_id)
516-
{
509+
if let Some(sender) = self.waiting_map.lock()?.remove(&resp_id) {
517510
sender
518511
.send(ChannelMessage::Response(resp))
519512
.expect("Unable to send the response");
@@ -556,13 +549,13 @@ impl<S: Read + Write> RawClient<S> {
556549
// Add our listener to the map before we send the request, to make sure we don't get a
557550
// reply before the receiver is added
558551
let (sender, receiver) = channel();
559-
self.waiting_map.lock().unwrap().insert(req.id, sender);
552+
self.waiting_map.lock()?.insert(req.id, sender);
560553

561554
let mut raw = serde_json::to_vec(&req)?;
562555
trace!("==> {}", String::from_utf8_lossy(&raw));
563556

564557
raw.extend_from_slice(b"\n");
565-
let mut stream = self.stream.lock().unwrap();
558+
let mut stream = self.stream.lock()?;
566559
stream.write_all(&raw)?;
567560
stream.flush()?;
568561
drop(stream); // release the lock
@@ -574,7 +567,7 @@ impl<S: Read + Write> RawClient<S> {
574567
e @ Err(_) => {
575568
// In case of error our sender could still be left in the map, depending on where
576569
// the error happened. Just in case, try to remove it here
577-
self.waiting_map.lock().unwrap().remove(&req.id);
570+
self.waiting_map.lock()?.remove(&req.id);
578571
return e;
579572
}
580573
};
@@ -617,14 +610,14 @@ impl<S: Read + Write> RawClient<S> {
617610

618611
fn handle_notification(&self, method: &str, result: serde_json::Value) -> Result<(), Error> {
619612
match method {
620-
"blockchain.headers.subscribe" => self.headers.lock().unwrap().append(
613+
"blockchain.headers.subscribe" => self.headers.lock()?.append(
621614
&mut serde_json::from_value::<Vec<RawHeaderNotification>>(result)?
622615
.into_iter()
623616
.collect(),
624617
),
625618
"blockchain.scripthash.subscribe" => {
626619
let unserialized: ScriptNotification = serde_json::from_value(result)?;
627-
let mut script_notifications = self.script_notifications.lock().unwrap();
620+
let mut script_notifications = self.script_notifications.lock()?;
628621

629622
let queue = script_notifications
630623
.get_mut(&unserialized.scripthash)
@@ -668,10 +661,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
668661
);
669662
missing_responses.insert(req.id);
670663

671-
self.waiting_map
672-
.lock()
673-
.unwrap()
674-
.insert(req.id, sender.clone());
664+
self.waiting_map.lock()?.insert(req.id, sender.clone());
675665

676666
raw.append(&mut serde_json::to_vec(&req)?);
677667
raw.extend_from_slice(b"\n");
@@ -683,7 +673,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
683673

684674
trace!("==> {}", String::from_utf8_lossy(&raw));
685675

686-
let mut stream = self.stream.lock().unwrap();
676+
let mut stream = self.stream.lock()?;
687677
stream.write_all(&raw)?;
688678
stream.flush()?;
689679
drop(stream); // release the lock
@@ -699,7 +689,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
699689
// the error happened. Just in case, try to remove it here
700690
warn!("got error for req_id {}: {:?}", req_id, e);
701691
warn!("removing all waiting req of this batch");
702-
let mut guard = self.waiting_map.lock().unwrap();
692+
let mut guard = self.waiting_map.lock()?;
703693
for req_id in missing_responses.iter() {
704694
guard.remove(&req_id);
705695
}
@@ -730,7 +720,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
730720
}
731721

732722
fn block_headers_pop_raw(&self) -> Result<Option<RawHeaderNotification>, Error> {
733-
Ok(self.headers.lock().unwrap().pop_front())
723+
Ok(self.headers.lock()?.pop_front())
734724
}
735725

736726
fn block_header_raw(&self, height: usize) -> Result<Vec<u8>, Error> {
@@ -796,7 +786,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
796786

797787
fn script_subscribe(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
798788
let script_hash = script.to_electrum_scripthash();
799-
let mut script_notifications = self.script_notifications.lock().unwrap();
789+
let mut script_notifications = self.script_notifications.lock()?;
800790

801791
if script_notifications.contains_key(&script_hash) {
802792
return Err(Error::AlreadySubscribed(script_hash));
@@ -816,7 +806,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
816806

817807
fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
818808
let script_hash = script.to_electrum_scripthash();
819-
let mut script_notifications = self.script_notifications.lock().unwrap();
809+
let mut script_notifications = self.script_notifications.lock()?;
820810

821811
if !script_notifications.contains_key(&script_hash) {
822812
return Err(Error::NotSubscribed(script_hash));
@@ -838,12 +828,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
838828
fn script_pop(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
839829
let script_hash = script.to_electrum_scripthash();
840830

841-
match self
842-
.script_notifications
843-
.lock()
844-
.unwrap()
845-
.get_mut(&script_hash)
846-
{
831+
match self.script_notifications.lock()?.get_mut(&script_hash) {
847832
None => Err(Error::NotSubscribed(script_hash)),
848833
Some(queue) => Ok(queue.pop_front()),
849834
}

src/stream.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,26 @@ pub struct ClonableStream<T: Read + Write>(Arc<Mutex<T>>);
66

77
impl<T: Read + Write> Read for ClonableStream<T> {
88
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
9-
self.0.lock().unwrap().read(buf)
9+
self.0
10+
.lock()
11+
.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?
12+
.read(buf)
1013
}
1114
}
1215

1316
impl<T: Read + Write> Write for ClonableStream<T> {
1417
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
15-
self.0.lock().unwrap().write(buf)
18+
self.0
19+
.lock()
20+
.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?
21+
.write(buf)
1622
}
1723

1824
fn flush(&mut self) -> io::Result<()> {
19-
self.0.lock().unwrap().flush()
25+
self.0
26+
.lock()
27+
.map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?
28+
.flush()
2029
}
2130
}
2231

src/types.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use bitcoin::hashes::{sha256, Hash};
1414
use bitcoin::{Script, Txid};
1515

1616
use serde::{de, Deserialize, Serialize};
17+
use std::sync::PoisonError;
1718

1819
static JSONRPC_2_0: &str = "2.0";
1920

@@ -362,3 +363,9 @@ impl_error!(std::io::Error, IOError);
362363
impl_error!(serde_json::Error, JSON);
363364
impl_error!(bitcoin::hashes::hex::Error, Hex);
364365
impl_error!(bitcoin::consensus::encode::Error, Bitcoin);
366+
367+
impl<T> From<std::sync::PoisonError<T>> for Error {
368+
fn from(_: PoisonError<T>) -> Self {
369+
Error::CouldntLockReader
370+
}
371+
}

0 commit comments

Comments
 (0)