-
Notifications
You must be signed in to change notification settings - Fork 64
/
raw_client.rs
1347 lines (1150 loc) · 46.9 KB
/
raw_client.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Raw client
//!
//! This module contains the definition of the raw client that wraps the transport method
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::mem::drop;
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex, TryLockError};
use std::time::Duration;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use bitcoin::consensus::encode::deserialize;
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::{Script, Txid};
#[cfg(feature = "use-openssl")]
use openssl::ssl::{SslConnector, SslMethod, SslStream, SslVerifyMode};
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
not(feature = "use-openssl")
))]
use rustls::{
ClientConfig, ClientConnection, OwnedTrustAnchor, RootCertStore, ServerName, StreamOwned,
};
#[cfg(any(feature = "default", feature = "proxy"))]
use crate::socks::{Socks5Stream, TargetAddr, ToTargetAddr};
use stream::ClonableStream;
use api::ElectrumApi;
use batch::Batch;
use types::*;
macro_rules! impl_batch_call {
( $self:expr, $data:expr, $call:ident ) => {{
let mut batch = Batch::default();
for i in $data {
batch.$call(i);
}
let resp = $self.batch_call(&batch)?;
let mut answer = Vec::new();
for x in resp {
answer.push(serde_json::from_value(x)?);
}
Ok(answer)
}};
}
/// A trait for [`ToSocketAddrs`](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html) that
/// can also be turned into a domain. Used when an SSL client needs to validate the server's
/// certificate.
pub trait ToSocketAddrsDomain: ToSocketAddrs {
/// Returns the domain, if present
fn domain(&self) -> Option<&str> {
None
}
}
impl ToSocketAddrsDomain for &str {
fn domain(&self) -> Option<&str> {
self.splitn(2, ':').next()
}
}
impl ToSocketAddrsDomain for (&str, u16) {
fn domain(&self) -> Option<&str> {
self.0.domain()
}
}
#[cfg(any(feature = "default", feature = "proxy"))]
impl ToSocketAddrsDomain for TargetAddr {
fn domain(&self) -> Option<&str> {
match self {
TargetAddr::Ip(_) => None,
TargetAddr::Domain(domain, _) => Some(domain.as_str()),
}
}
}
macro_rules! impl_to_socket_addrs_domain {
( $ty:ty ) => {
impl ToSocketAddrsDomain for $ty {}
};
}
impl_to_socket_addrs_domain!(std::net::SocketAddr);
impl_to_socket_addrs_domain!(std::net::SocketAddrV4);
impl_to_socket_addrs_domain!(std::net::SocketAddrV6);
impl_to_socket_addrs_domain!((std::net::IpAddr, u16));
impl_to_socket_addrs_domain!((std::net::Ipv4Addr, u16));
impl_to_socket_addrs_domain!((std::net::Ipv6Addr, u16));
/// Instance of an Electrum client
///
/// A `Client` maintains a constant connection with an Electrum server and exposes methods to
/// interact with it. It can also subscribe and receive notifictations from the server about new
/// blocks or activity on a specific *scriptPubKey*.
///
/// The `Client` is modeled in such a way that allows the external caller to have full control over
/// its functionality: no threads or tasks are spawned internally to monitor the state of the
/// connection.
///
/// More transport methods can be used by manually creating an instance of this struct with an
/// arbitray `S` type.
#[derive(Debug)]
pub struct RawClient<S>
where
S: Read + Write,
{
stream: Mutex<ClonableStream<S>>,
buf_reader: Mutex<BufReader<ClonableStream<S>>>,
last_id: AtomicUsize,
waiting_map: Mutex<HashMap<usize, Sender<ChannelMessage>>>,
headers: Mutex<VecDeque<RawHeaderNotification>>,
script_notifications: Mutex<HashMap<ScriptHash, VecDeque<ScriptStatus>>>,
#[cfg(feature = "debug-calls")]
calls: AtomicUsize,
}
impl<S> From<S> for RawClient<S>
where
S: Read + Write,
{
fn from(stream: S) -> Self {
let stream: ClonableStream<_> = stream.into();
Self {
buf_reader: Mutex::new(BufReader::new(stream.clone())),
stream: Mutex::new(stream),
last_id: AtomicUsize::new(0),
waiting_map: Mutex::new(HashMap::new()),
headers: Mutex::new(VecDeque::new()),
script_notifications: Mutex::new(HashMap::new()),
#[cfg(feature = "debug-calls")]
calls: AtomicUsize::new(0),
}
}
}
/// Transport type used to establish a plaintext TCP connection with the server
pub type ElectrumPlaintextStream = TcpStream;
impl RawClient<ElectrumPlaintextStream> {
/// Creates a new plaintext client and tries to connect to `socket_addr`.
pub fn new<A: ToSocketAddrs>(
socket_addrs: A,
timeout: Option<Duration>,
) -> Result<Self, Error> {
let stream = match timeout {
Some(timeout) => {
let stream = connect_with_total_timeout(socket_addrs, timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
stream
}
None => TcpStream::connect(socket_addrs)?,
};
Ok(stream.into())
}
}
fn connect_with_total_timeout<A: ToSocketAddrs>(
socket_addrs: A,
mut timeout: Duration,
) -> Result<TcpStream, Error> {
// Use the same algorithm as curl: 1/2 on the first host, 1/4 on the second one, etc.
// https://curl.se/mail/lib-2014-11/0164.html
let mut errors = Vec::new();
let addrs = socket_addrs
.to_socket_addrs()?
.enumerate()
.collect::<Vec<_>>();
for (index, addr) in &addrs {
if *index < addrs.len() - 1 {
timeout = timeout.div_f32(2.0);
}
info!(
"Trying to connect to {} (attempt {}/{}) with timeout {:?}",
addr,
index + 1,
addrs.len(),
timeout
);
match TcpStream::connect_timeout(addr, timeout) {
Ok(socket) => return Ok(socket),
Err(e) => {
warn!("Connection error: {:?}", e);
errors.push(e.into());
}
}
}
Err(Error::AllAttemptsErrored(errors))
}
#[cfg(feature = "use-openssl")]
/// Transport type used to establish an OpenSSL TLS encrypted/authenticated connection with the server
pub type ElectrumSslStream = SslStream<TcpStream>;
#[cfg(feature = "use-openssl")]
impl RawClient<ElectrumSslStream> {
/// Creates a new SSL client and tries to connect to `socket_addr`. Optionally, if
/// `validate_domain` is `true`, validate the server's certificate.
pub fn new_ssl<A: ToSocketAddrsDomain + Clone>(
socket_addrs: A,
validate_domain: bool,
timeout: Option<Duration>,
) -> Result<Self, Error> {
debug!(
"new_ssl socket_addrs.domain():{:?} validate_domain:{} timeout:{:?}",
socket_addrs.domain(),
validate_domain,
timeout
);
if validate_domain {
socket_addrs.domain().ok_or(Error::MissingDomain)?;
}
match timeout {
Some(timeout) => {
let stream = connect_with_total_timeout(socket_addrs.clone(), timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
}
None => {
let stream = TcpStream::connect(socket_addrs.clone())?;
Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
}
}
}
/// Create a new SSL client using an existing TcpStream
pub fn new_ssl_from_stream<A: ToSocketAddrsDomain>(
socket_addrs: A,
validate_domain: bool,
stream: TcpStream,
) -> Result<Self, Error> {
let mut builder =
SslConnector::builder(SslMethod::tls()).map_err(Error::InvalidSslMethod)?;
// TODO: support for certificate pinning
if validate_domain {
socket_addrs.domain().ok_or(Error::MissingDomain)?;
} else {
builder.set_verify(SslVerifyMode::NONE);
}
let connector = builder.build();
let domain = socket_addrs.domain().unwrap_or("NONE").to_string();
let stream = connector
.connect(&domain, stream)
.map_err(Error::SslHandshakeError)?;
Ok(stream.into())
}
}
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
not(feature = "use-openssl")
))]
mod danger {
use rustls;
use rustls::client::ServerCertVerified;
use rustls::{Certificate, Error, ServerName};
use std::time::SystemTime;
pub struct NoCertificateVerification {}
impl rustls::client::ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_end_entity: &Certificate,
_intermediates: &[Certificate],
_server_name: &ServerName,
_scts: &mut dyn Iterator<Item = &[u8]>,
_ocsp_response: &[u8],
_now: SystemTime,
) -> Result<ServerCertVerified, Error> {
Ok(ServerCertVerified::assertion())
}
}
}
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
not(feature = "use-openssl")
))]
/// Transport type used to establish a Rustls TLS encrypted/authenticated connection with the server
pub type ElectrumSslStream = StreamOwned<ClientConnection, TcpStream>;
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
not(feature = "use-openssl")
))]
impl RawClient<ElectrumSslStream> {
/// Creates a new SSL client and tries to connect to `socket_addr`. Optionally, if
/// `validate_domain` is `true`, validate the server's certificate.
pub fn new_ssl<A: ToSocketAddrsDomain + Clone>(
socket_addrs: A,
validate_domain: bool,
timeout: Option<Duration>,
) -> Result<Self, Error> {
debug!(
"new_ssl socket_addrs.domain():{:?} validate_domain:{} timeout:{:?}",
socket_addrs.domain(),
validate_domain,
timeout
);
if validate_domain {
socket_addrs.domain().ok_or(Error::MissingDomain)?;
}
match timeout {
Some(timeout) => {
let stream = connect_with_total_timeout(socket_addrs.clone(), timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
}
None => {
let stream = TcpStream::connect(socket_addrs.clone())?;
Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
}
}
}
/// Create a new SSL client using an existing TcpStream
pub fn new_ssl_from_stream<A: ToSocketAddrsDomain>(
socket_addr: A,
validate_domain: bool,
tcp_stream: TcpStream,
) -> Result<Self, Error> {
use std::convert::TryFrom;
let builder = ClientConfig::builder().with_safe_defaults();
let config = if validate_domain {
socket_addr.domain().ok_or(Error::MissingDomain)?;
let mut store = RootCertStore::empty();
store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.into_iter().map(|t| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
t.subject,
t.spki,
t.name_constraints,
)
}));
// TODO: cert pinning
builder.with_root_certificates(store).with_no_client_auth()
} else {
builder
.with_custom_certificate_verifier(std::sync::Arc::new(
danger::NoCertificateVerification {},
))
.with_no_client_auth()
};
let domain = socket_addr.domain().unwrap_or("NONE").to_string();
let session = ClientConnection::new(
std::sync::Arc::new(config),
ServerName::try_from(domain.as_str())
.map_err(|_| Error::InvalidDNSNameError(domain.clone()))?,
)
.map_err(Error::CouldNotCreateConnection)?;
let stream = StreamOwned::new(session, tcp_stream);
Ok(stream.into())
}
}
#[cfg(any(feature = "default", feature = "proxy"))]
/// Transport type used to establish a connection to a server through a socks proxy
pub type ElectrumProxyStream = Socks5Stream;
#[cfg(any(feature = "default", feature = "proxy"))]
impl RawClient<ElectrumProxyStream> {
/// Creates a new socks client and tries to connect to `target_addr` using `proxy_addr` as a
/// socks proxy server. The DNS resolution of `target_addr`, if required, is done
/// through the proxy. This allows to specify, for instance, `.onion` addresses.
pub fn new_proxy<T: ToTargetAddr>(
target_addr: T,
proxy: &crate::Socks5Config,
timeout: Option<Duration>,
) -> Result<Self, Error> {
let mut stream = match proxy.credentials.as_ref() {
Some(cred) => Socks5Stream::connect_with_password(
&proxy.addr,
target_addr,
&cred.username,
&cred.password,
timeout,
)?,
None => Socks5Stream::connect(&proxy.addr, target_addr, timeout)?,
};
stream.get_mut().set_read_timeout(timeout)?;
stream.get_mut().set_write_timeout(timeout)?;
Ok(stream.into())
}
#[cfg(any(feature = "use-openssl", feature = "use-rustls"))]
/// Creates a new TLS client that connects to `target_addr` using `proxy_addr` as a socks proxy
/// server. The DNS resolution of `target_addr`, if required, is done through the proxy. This
/// allows to specify, for instance, `.onion` addresses.
pub fn new_proxy_ssl<T: ToTargetAddr>(
target_addr: T,
validate_domain: bool,
proxy: &crate::Socks5Config,
timeout: Option<Duration>,
) -> Result<RawClient<ElectrumSslStream>, Error> {
let target = target_addr.to_target_addr()?;
let mut stream = match proxy.credentials.as_ref() {
Some(cred) => Socks5Stream::connect_with_password(
&proxy.addr,
target_addr,
&cred.username,
&cred.password,
timeout,
)?,
None => Socks5Stream::connect(&proxy.addr, target.clone(), timeout)?,
};
stream.get_mut().set_read_timeout(timeout)?;
stream.get_mut().set_write_timeout(timeout)?;
RawClient::new_ssl_from_stream(target, validate_domain, stream.into_inner())
}
}
#[derive(Debug)]
enum ChannelMessage {
Response(serde_json::Value),
WakeUp,
Error(Arc<std::io::Error>),
}
impl<S: Read + Write> RawClient<S> {
// TODO: to enable this we have to find a way to allow concurrent read and writes to the
// underlying transport struct. This can be done pretty easily for TcpStream because it can be
// split into a "read" and a "write" object, but it's not as trivial for other types. Without
// such thing, this causes a deadlock, because the reader thread takes a lock on the
// `ClonableStream` before other threads can send a request to the server. They will block
// waiting for the reader to release the mutex, but this will never happen because the server
// didn't receive any request, so it has nothing to send back.
// pub fn reader_thread(&self) -> Result<(), Error> {
// self._reader_thread(None).map(|_| ())
// }
fn _reader_thread(&self, until_message: Option<usize>) -> Result<serde_json::Value, Error> {
let mut raw_resp = String::new();
let resp = match self.buf_reader.try_lock() {
Ok(mut reader) => {
trace!(
"Starting reader thread with `until_message` = {:?}",
until_message
);
if let Some(until_message) = until_message {
// If we are trying to start a reader thread but the corresponding sender is
// missing from the map, exit immediately. This can happen with batch calls,
// since the sender is shared for all the individual queries in a call. We
// might have already received a response for that id, but we don't know it
// yet. Exiting here forces the calling code to fallback to the sender-receiver
// method, and it should find a message there waiting for it.
if self.waiting_map.lock()?.get(&until_message).is_none() {
return Err(Error::CouldntLockReader);
}
}
// Loop over every message
loop {
raw_resp.clear();
if let Err(e) = reader.read_line(&mut raw_resp) {
let error = Arc::new(e);
for (_, s) in self.waiting_map.lock().unwrap().drain() {
s.send(ChannelMessage::Error(error.clone()))?;
}
return Err(Error::SharedIOError(error));
}
trace!("<== {}", raw_resp);
let resp: serde_json::Value = serde_json::from_str(&raw_resp)?;
// Normally there is and id, but it's missing for spontaneous notifications
// from the server
let resp_id = resp["id"]
.as_str()
.and_then(|s| s.parse().ok())
.or_else(|| resp["id"].as_u64().map(|i| i as usize));
match resp_id {
Some(resp_id) if until_message == Some(resp_id) => {
// We have a valid id and it's exactly the one we were waiting for!
trace!(
"Reader thread {} received a response for its request",
resp_id
);
// Remove ourselves from the "waiting map"
let mut map = self.waiting_map.lock()?;
map.remove(&resp_id);
// If the map is not empty, we select a random thread to become the
// new reader thread.
if let Some(err) = map.values().find_map(|sender| {
sender
.send(ChannelMessage::WakeUp)
.map_err(|err| {
warn!("Unable to wake up a thread, trying some other");
err
})
.err()
}) {
error!("All the threads has failed, giving up");
return Err(err)?;
}
break Ok(resp);
}
Some(resp_id) => {
// We have an id, but it's not our response. Notify the thread and
// move on
trace!("Reader thread received response for {}", resp_id);
if let Some(sender) = self.waiting_map.lock()?.remove(&resp_id) {
sender.send(ChannelMessage::Response(resp))?;
} else {
warn!("Missing listener for {}", resp_id);
}
}
None => {
// No id, that's probably a notification.
let mut resp = resp;
if let Some(ref method) = resp["method"].take().as_str() {
self.handle_notification(method, resp["params"].take())?;
} else {
warn!("Unexpected response: {:?}", resp);
}
}
}
}
}
Err(TryLockError::WouldBlock) => {
// If we "WouldBlock" here it means that there's already a reader thread
// running somewhere.
Err(Error::CouldntLockReader)
}
Err(TryLockError::Poisoned(e)) => Err(e)?,
};
let resp = resp?;
if let Some(err) = resp.get("error") {
Err(Error::Protocol(err.clone()))
} else {
Ok(resp)
}
}
fn call(&self, req: Request) -> Result<serde_json::Value, Error> {
// Add our listener to the map before we send the request, to make sure we don't get a
// reply before the receiver is added
let (sender, receiver) = channel();
self.waiting_map.lock()?.insert(req.id, sender);
let mut raw = serde_json::to_vec(&req)?;
trace!("==> {}", String::from_utf8_lossy(&raw));
raw.extend_from_slice(b"\n");
let mut stream = self.stream.lock()?;
stream.write_all(&raw)?;
stream.flush()?;
drop(stream); // release the lock
self.increment_calls();
let mut resp = match self.recv(&receiver, req.id) {
Ok(resp) => resp,
e @ Err(_) => {
// In case of error our sender could still be left in the map, depending on where
// the error happened. Just in case, try to remove it here
self.waiting_map.lock()?.remove(&req.id);
return e;
}
};
Ok(resp["result"].take())
}
fn recv(
&self,
receiver: &Receiver<ChannelMessage>,
req_id: usize,
) -> Result<serde_json::Value, Error> {
loop {
// Try to take the lock on the reader. If we manage to do so, we'll become the reader
// thread until we get our reponse
match self._reader_thread(Some(req_id)) {
Ok(response) => break Ok(response),
Err(Error::CouldntLockReader) => {
match receiver.recv()? {
// Received our response, returning it
ChannelMessage::Response(received) => break Ok(received),
ChannelMessage::WakeUp => {
// We have been woken up, this means that we should try becoming the
// reader thread ourselves
trace!("WakeUp for {}", req_id);
continue;
}
ChannelMessage::Error(e) => {
warn!("Received ChannelMessage::Error");
break Err(Error::SharedIOError(e));
}
}
}
e @ Err(_) => break e,
}
}
}
fn handle_notification(&self, method: &str, result: serde_json::Value) -> Result<(), Error> {
match method {
"blockchain.headers.subscribe" => self.headers.lock()?.append(
&mut serde_json::from_value::<Vec<RawHeaderNotification>>(result)?
.into_iter()
.collect(),
),
"blockchain.scripthash.subscribe" => {
let unserialized: ScriptNotification = serde_json::from_value(result)?;
let mut script_notifications = self.script_notifications.lock()?;
let queue = script_notifications
.get_mut(&unserialized.scripthash)
.ok_or(Error::NotSubscribed(unserialized.scripthash))?;
queue.push_back(unserialized.status);
}
_ => info!("received unknown notification for method `{}`", method),
}
Ok(())
}
pub(crate) fn internal_raw_call_with_vec(
&self,
method_name: &str,
params: Vec<Param>,
) -> Result<serde_json::Value, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
&method_name,
params,
);
let result = self.call(req)?;
Ok(result)
}
#[inline]
#[cfg(feature = "debug-calls")]
fn increment_calls(&self) {
self.calls.fetch_add(1, Ordering::SeqCst);
}
#[inline]
#[cfg(not(feature = "debug-calls"))]
fn increment_calls(&self) {}
}
impl<T: Read + Write> ElectrumApi for RawClient<T> {
fn raw_call(
&self,
method_name: &str,
params: impl IntoIterator<Item = Param>,
) -> Result<serde_json::Value, Error> {
self.internal_raw_call_with_vec(method_name, params.into_iter().collect())
}
fn batch_call(&self, batch: &Batch) -> Result<Vec<serde_json::Value>, Error> {
let mut raw = Vec::new();
let mut missing_responses = BTreeSet::new();
let mut answers = BTreeMap::new();
// Add our listener to the map before we send the request, Here we will clone the sender
// for every request id, so that we only have to monitor one receiver.
let (sender, receiver) = channel();
for (method, params) in batch.iter() {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
&method,
params.to_vec(),
);
missing_responses.insert(req.id);
self.waiting_map.lock()?.insert(req.id, sender.clone());
raw.append(&mut serde_json::to_vec(&req)?);
raw.extend_from_slice(b"\n");
}
if missing_responses.is_empty() {
return Ok(vec![]);
}
trace!("==> {}", String::from_utf8_lossy(&raw));
let mut stream = self.stream.lock()?;
stream.write_all(&raw)?;
stream.flush()?;
drop(stream); // release the lock
self.increment_calls();
for req_id in missing_responses.iter() {
match self.recv(&receiver, *req_id) {
Ok(mut resp) => answers.insert(req_id, resp["result"].take()),
Err(e) => {
// In case of error our sender could still be left in the map, depending on where
// the error happened. Just in case, try to remove it here
warn!("got error for req_id {}: {:?}", req_id, e);
warn!("removing all waiting req of this batch");
let mut guard = self.waiting_map.lock()?;
for req_id in missing_responses.iter() {
guard.remove(req_id);
}
return Err(e);
}
};
}
Ok(answers.into_iter().map(|(_, r)| r).collect())
}
fn block_headers_subscribe_raw(&self) -> Result<RawHeaderNotification, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.headers.subscribe",
vec![],
);
let value = self.call(req)?;
Ok(serde_json::from_value(value)?)
}
fn block_headers_pop_raw(&self) -> Result<Option<RawHeaderNotification>, Error> {
Ok(self.headers.lock()?.pop_front())
}
fn block_header_raw(&self, height: usize) -> Result<Vec<u8>, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.block.header",
vec![Param::Usize(height)],
);
let result = self.call(req)?;
Ok(Vec::<u8>::from_hex(
result
.as_str()
.ok_or_else(|| Error::InvalidResponse(result.clone()))?,
)?)
}
fn block_headers(&self, start_height: usize, count: usize) -> Result<GetHeadersRes, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.block.headers",
vec![Param::Usize(start_height), Param::Usize(count)],
);
let result = self.call(req)?;
let mut deserialized: GetHeadersRes = serde_json::from_value(result)?;
for i in 0..deserialized.count {
let (start, end) = (i * 80, (i + 1) * 80);
deserialized
.headers
.push(deserialize(&deserialized.raw_headers[start..end])?);
}
deserialized.raw_headers.clear();
Ok(deserialized)
}
fn estimate_fee(&self, number: usize) -> Result<f64, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.estimatefee",
vec![Param::Usize(number)],
);
let result = self.call(req)?;
result
.as_f64()
.ok_or_else(|| Error::InvalidResponse(result.clone()))
}
fn relay_fee(&self) -> Result<f64, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.relayfee",
vec![],
);
let result = self.call(req)?;
result
.as_f64()
.ok_or_else(|| Error::InvalidResponse(result.clone()))
}
fn script_subscribe(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
let script_hash = script.to_electrum_scripthash();
let mut script_notifications = self.script_notifications.lock()?;
if script_notifications.contains_key(&script_hash) {
return Err(Error::AlreadySubscribed(script_hash));
}
script_notifications.insert(script_hash, VecDeque::new());
drop(script_notifications);
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.scripthash.subscribe",
vec![Param::String(script_hash.to_hex())],
);
let value = self.call(req)?;
Ok(serde_json::from_value(value)?)
}
fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
let script_hash = script.to_electrum_scripthash();
let mut script_notifications = self.script_notifications.lock()?;
if !script_notifications.contains_key(&script_hash) {
return Err(Error::NotSubscribed(script_hash));
}
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.scripthash.unsubscribe",
vec![Param::String(script_hash.to_hex())],
);
let value = self.call(req)?;
let answer = serde_json::from_value(value)?;
script_notifications.remove(&script_hash);
Ok(answer)
}
fn script_pop(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
let script_hash = script.to_electrum_scripthash();
match self.script_notifications.lock()?.get_mut(&script_hash) {
None => Err(Error::NotSubscribed(script_hash)),
Some(queue) => Ok(queue.pop_front()),
}
}
fn script_get_balance(&self, script: &Script) -> Result<GetBalanceRes, Error> {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.scripthash.get_balance",
params,
);
let result = self.call(req)?;
Ok(serde_json::from_value(result)?)
}
fn batch_script_get_balance<'s, I>(&self, scripts: I) -> Result<Vec<GetBalanceRes>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone,
{
impl_batch_call!(self, scripts, script_get_balance)
}
fn script_get_history(&self, script: &Script) -> Result<Vec<GetHistoryRes>, Error> {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.scripthash.get_history",
params,
);
let result = self.call(req)?;
Ok(serde_json::from_value(result)?)
}
fn batch_script_get_history<'s, I>(&self, scripts: I) -> Result<Vec<Vec<GetHistoryRes>>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone,
{
impl_batch_call!(self, scripts, script_get_history)
}
fn script_list_unspent(&self, script: &Script) -> Result<Vec<ListUnspentRes>, Error> {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.scripthash.listunspent",
params,
);
let result = self.call(req)?;
let mut result: Vec<ListUnspentRes> = serde_json::from_value(result)?;
// This should not be necessary, since the protocol documentation says that the txs should
// be "in blockchain order" (https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-listunspent).
// However, elects seems to be ignoring this at the moment, so we'll sort again here just
// to make sure the result is consistent.
result.sort_unstable_by_key(|k| (k.height, k.tx_pos));
Ok(result)
}
fn batch_script_list_unspent<'s, I>(
&self,
scripts: I,
) -> Result<Vec<Vec<ListUnspentRes>>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone,
{
impl_batch_call!(self, scripts, script_list_unspent)
}
fn transaction_get_raw(&self, txid: &Txid) -> Result<Vec<u8>, Error> {
let params = vec![Param::String(txid.to_hex())];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.transaction.get",
params,
);
let result = self.call(req)?;
Ok(Vec::<u8>::from_hex(
result
.as_str()
.ok_or_else(|| Error::InvalidResponse(result.clone()))?,
)?)
}
fn batch_transaction_get_raw<'t, I>(&self, txids: I) -> Result<Vec<Vec<u8>>, Error>
where
I: IntoIterator<Item = &'t Txid> + Clone,
{
let txs_string: Result<Vec<String>, Error> = impl_batch_call!(self, txids, transaction_get);
txs_string?
.iter()
.map(|s| Ok(Vec::<u8>::from_hex(s)?))
.collect()
}
fn batch_block_header_raw<'s, I>(&self, heights: I) -> Result<Vec<Vec<u8>>, Error>
where
I: IntoIterator<Item = u32> + Clone,
{
let headers_string: Result<Vec<String>, Error> =
impl_batch_call!(self, heights, block_header);
headers_string?
.iter()
.map(|s| Ok(Vec::<u8>::from_hex(s)?))
.collect()
}
fn batch_estimate_fee<'s, I>(&self, numbers: I) -> Result<Vec<f64>, Error>
where
I: IntoIterator<Item = usize> + Clone,
{
impl_batch_call!(self, numbers, estimate_fee)
}
fn transaction_broadcast_raw(&self, raw_tx: &[u8]) -> Result<Txid, Error> {
let params = vec![Param::String(raw_tx.to_hex())];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.transaction.broadcast",
params,
);
let result = self.call(req)?;
Ok(serde_json::from_value(result)?)