Skip to main content

electrum_client/
raw_client.rs

1//! Raw client
2//!
3//! This module contains the definition of the raw client that wraps the transport method
4
5use std::borrow::Borrow;
6use std::collections::{BTreeMap, HashMap, VecDeque};
7use std::io::{BufRead, BufReader, Read, Write};
8use std::mem::drop;
9use std::net::{TcpStream, ToSocketAddrs};
10use std::sync::atomic::{AtomicUsize, Ordering};
11use std::sync::mpsc::{channel, Receiver, Sender};
12use std::sync::{Arc, Mutex, TryLockError};
13use std::time::Duration;
14
15#[allow(unused_imports)]
16use log::{debug, error, info, trace, warn};
17
18use bitcoin::consensus::encode::deserialize;
19use bitcoin::hex::{DisplayHex, FromHex};
20use bitcoin::{Script, Txid};
21
22#[cfg(feature = "use-openssl")]
23use openssl::ssl::{SslConnector, SslMethod, SslStream, SslVerifyMode};
24
25#[cfg(all(
26    any(
27        feature = "default",
28        feature = "use-rustls",
29        feature = "use-rustls-ring"
30    ),
31    not(feature = "use-openssl")
32))]
33use rustls::{pki_types::ServerName, ClientConfig, ClientConnection, RootCertStore, StreamOwned};
34
35#[cfg(any(feature = "default", feature = "proxy"))]
36use crate::socks::{Socks5Stream, TargetAddr, ToTargetAddr};
37
38use crate::stream::ClonableStream;
39
40use crate::api::ElectrumApi;
41use crate::batch::Batch;
42use crate::types::*;
43
44macro_rules! impl_batch_call {
45    ( $self:expr, $data:expr, $call:ident ) => {{
46        impl_batch_call!($self, $data, $call, )
47    }};
48
49    ( $self:expr, $data:expr, $call:ident, apply_deref ) => {{
50        impl_batch_call!($self, $data, $call, *)
51    }};
52
53    ( $self:expr, $data:expr, $call:ident, $($apply_deref:tt)? ) => {{
54        let mut batch = Batch::default();
55        for i in $data {
56            batch.$call($($apply_deref)* i.borrow());
57        }
58
59        let resp = $self.batch_call(&batch)?;
60        let mut answer = Vec::new();
61
62        for x in resp {
63            answer.push(serde_json::from_value(x)?);
64        }
65
66        Ok(answer)
67    }};
68}
69
70/// A trait for [`ToSocketAddrs`](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html) that
71/// can also be turned into a domain. Used when an SSL client needs to validate the server's
72/// certificate.
73pub trait ToSocketAddrsDomain: ToSocketAddrs {
74    /// Returns the domain, if present
75    fn domain(&self) -> Option<&str> {
76        None
77    }
78}
79
80impl ToSocketAddrsDomain for &str {
81    fn domain(&self) -> Option<&str> {
82        self.split(':').next()
83    }
84}
85
86impl ToSocketAddrsDomain for (&str, u16) {
87    fn domain(&self) -> Option<&str> {
88        self.0.domain()
89    }
90}
91
92#[cfg(any(feature = "default", feature = "proxy"))]
93impl ToSocketAddrsDomain for TargetAddr {
94    fn domain(&self) -> Option<&str> {
95        match self {
96            TargetAddr::Ip(_) => None,
97            TargetAddr::Domain(domain, _) => Some(domain.as_str()),
98        }
99    }
100}
101
102macro_rules! impl_to_socket_addrs_domain {
103    ( $ty:ty ) => {
104        impl ToSocketAddrsDomain for $ty {}
105    };
106}
107
108impl_to_socket_addrs_domain!(std::net::SocketAddr);
109impl_to_socket_addrs_domain!(std::net::SocketAddrV4);
110impl_to_socket_addrs_domain!(std::net::SocketAddrV6);
111impl_to_socket_addrs_domain!((std::net::IpAddr, u16));
112impl_to_socket_addrs_domain!((std::net::Ipv4Addr, u16));
113impl_to_socket_addrs_domain!((std::net::Ipv6Addr, u16));
114
115/// Instance of an Electrum client
116///
117/// A `Client` maintains a constant connection with an Electrum server and exposes methods to
118/// interact with it. It can also subscribe and receive notifictations from the server about new
119/// blocks or activity on a specific *scriptPubKey*.
120///
121/// The `Client` is modeled in such a way that allows the external caller to have full control over
122/// its functionality: no threads or tasks are spawned internally to monitor the state of the
123/// connection.
124///
125/// More transport methods can be used by manually creating an instance of this struct with an
126/// arbitray `S` type.
127#[derive(Debug)]
128pub struct RawClient<S>
129where
130    S: Read + Write,
131{
132    stream: Mutex<ClonableStream<S>>,
133    buf_reader: Mutex<BufReader<ClonableStream<S>>>,
134
135    last_id: AtomicUsize,
136    waiting_map: Mutex<HashMap<usize, Sender<ChannelMessage>>>,
137
138    headers: Mutex<VecDeque<RawHeaderNotification>>,
139    script_notifications: Mutex<HashMap<ScriptHash, VecDeque<ScriptStatus>>>,
140
141    #[cfg(feature = "debug-calls")]
142    calls: AtomicUsize,
143}
144
145impl<S> From<S> for RawClient<S>
146where
147    S: Read + Write,
148{
149    fn from(stream: S) -> Self {
150        let stream: ClonableStream<_> = stream.into();
151
152        Self {
153            buf_reader: Mutex::new(BufReader::new(stream.clone())),
154            stream: Mutex::new(stream),
155
156            last_id: AtomicUsize::new(0),
157            waiting_map: Mutex::new(HashMap::new()),
158
159            headers: Mutex::new(VecDeque::new()),
160            script_notifications: Mutex::new(HashMap::new()),
161
162            #[cfg(feature = "debug-calls")]
163            calls: AtomicUsize::new(0),
164        }
165    }
166}
167
168/// Transport type used to establish a plaintext TCP connection with the server
169pub type ElectrumPlaintextStream = TcpStream;
170impl RawClient<ElectrumPlaintextStream> {
171    /// Creates a new plaintext client and tries to connect to `socket_addr`.
172    pub fn new<A: ToSocketAddrs>(
173        socket_addrs: A,
174        timeout: Option<Duration>,
175    ) -> Result<Self, Error> {
176        let stream = match timeout {
177            Some(timeout) => {
178                let stream = connect_with_total_timeout(socket_addrs, timeout)?;
179                stream.set_read_timeout(Some(timeout))?;
180                stream.set_write_timeout(Some(timeout))?;
181                stream
182            }
183            None => TcpStream::connect(socket_addrs)?,
184        };
185
186        Ok(stream.into())
187    }
188}
189
190fn connect_with_total_timeout<A: ToSocketAddrs>(
191    socket_addrs: A,
192    mut timeout: Duration,
193) -> Result<TcpStream, Error> {
194    // Use the same algorithm as curl: 1/2 on the first host, 1/4 on the second one, etc.
195    // https://curl.se/mail/lib-2014-11/0164.html
196
197    let mut errors = Vec::new();
198
199    let addrs = socket_addrs
200        .to_socket_addrs()?
201        .enumerate()
202        .collect::<Vec<_>>();
203    for (index, addr) in &addrs {
204        if *index < addrs.len() - 1 {
205            timeout = timeout.div_f32(2.0);
206        }
207
208        info!(
209            "Trying to connect to {} (attempt {}/{}) with timeout {:?}",
210            addr,
211            index + 1,
212            addrs.len(),
213            timeout
214        );
215        match TcpStream::connect_timeout(addr, timeout) {
216            Ok(socket) => return Ok(socket),
217            Err(e) => {
218                warn!("Connection error: {:?}", e);
219                errors.push(e.into());
220            }
221        }
222    }
223
224    Err(Error::AllAttemptsErrored(errors))
225}
226
227#[cfg(feature = "use-openssl")]
228/// Transport type used to establish an OpenSSL TLS encrypted/authenticated connection with the server
229pub type ElectrumSslStream = SslStream<TcpStream>;
230#[cfg(feature = "use-openssl")]
231impl RawClient<ElectrumSslStream> {
232    /// Creates a new SSL client and tries to connect to `socket_addr`. Optionally, if
233    /// `validate_domain` is `true`, validate the server's certificate.
234    pub fn new_ssl<A: ToSocketAddrsDomain + Clone>(
235        socket_addrs: A,
236        validate_domain: bool,
237        timeout: Option<Duration>,
238    ) -> Result<Self, Error> {
239        debug!(
240            "new_ssl socket_addrs.domain():{:?} validate_domain:{} timeout:{:?}",
241            socket_addrs.domain(),
242            validate_domain,
243            timeout
244        );
245        if validate_domain {
246            socket_addrs.domain().ok_or(Error::MissingDomain)?;
247        }
248        match timeout {
249            Some(timeout) => {
250                let stream = connect_with_total_timeout(socket_addrs.clone(), timeout)?;
251                stream.set_read_timeout(Some(timeout))?;
252                stream.set_write_timeout(Some(timeout))?;
253                Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
254            }
255            None => {
256                let stream = TcpStream::connect(socket_addrs.clone())?;
257                Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
258            }
259        }
260    }
261
262    /// Create a new SSL client using an existing TcpStream
263    pub fn new_ssl_from_stream<A: ToSocketAddrsDomain>(
264        socket_addrs: A,
265        validate_domain: bool,
266        stream: TcpStream,
267    ) -> Result<Self, Error> {
268        let mut builder =
269            SslConnector::builder(SslMethod::tls()).map_err(Error::InvalidSslMethod)?;
270        // TODO: support for certificate pinning
271        if validate_domain {
272            socket_addrs.domain().ok_or(Error::MissingDomain)?;
273        } else {
274            builder.set_verify(SslVerifyMode::NONE);
275        }
276        let connector = builder.build();
277
278        let domain = socket_addrs.domain().unwrap_or("NONE").to_string();
279
280        let stream = connector
281            .connect(&domain, stream)
282            .map_err(Error::SslHandshakeError)?;
283
284        Ok(stream.into())
285    }
286}
287
288#[cfg(all(
289    any(
290        feature = "default",
291        feature = "use-rustls",
292        feature = "use-rustls-ring"
293    ),
294    not(feature = "use-openssl")
295))]
296mod danger {
297    use crate::raw_client::ServerName;
298    use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified};
299    use rustls::crypto::CryptoProvider;
300    use rustls::pki_types::{CertificateDer, UnixTime};
301    use rustls::DigitallySignedStruct;
302
303    #[derive(Debug)]
304    pub struct NoCertificateVerification(CryptoProvider);
305
306    impl NoCertificateVerification {
307        pub fn new(provider: CryptoProvider) -> Self {
308            Self(provider)
309        }
310    }
311
312    impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
313        fn verify_server_cert(
314            &self,
315            _end_entity: &CertificateDer<'_>,
316            _intermediates: &[CertificateDer<'_>],
317            _server_name: &ServerName<'_>,
318            _ocsp: &[u8],
319            _now: UnixTime,
320        ) -> Result<ServerCertVerified, rustls::Error> {
321            Ok(ServerCertVerified::assertion())
322        }
323
324        fn verify_tls12_signature(
325            &self,
326            _message: &[u8],
327            _cert: &CertificateDer<'_>,
328            _dss: &DigitallySignedStruct,
329        ) -> Result<HandshakeSignatureValid, rustls::Error> {
330            Ok(HandshakeSignatureValid::assertion())
331        }
332
333        fn verify_tls13_signature(
334            &self,
335            _message: &[u8],
336            _cert: &CertificateDer<'_>,
337            _dss: &DigitallySignedStruct,
338        ) -> Result<HandshakeSignatureValid, rustls::Error> {
339            Ok(HandshakeSignatureValid::assertion())
340        }
341
342        fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
343            self.0.signature_verification_algorithms.supported_schemes()
344        }
345    }
346}
347
348#[cfg(all(
349    any(
350        feature = "default",
351        feature = "use-rustls",
352        feature = "use-rustls-ring"
353    ),
354    not(feature = "use-openssl")
355))]
356/// Transport type used to establish a Rustls TLS encrypted/authenticated connection with the server
357pub type ElectrumSslStream = StreamOwned<ClientConnection, TcpStream>;
358#[cfg(all(
359    any(
360        feature = "default",
361        feature = "use-rustls",
362        feature = "use-rustls-ring"
363    ),
364    not(feature = "use-openssl")
365))]
366impl RawClient<ElectrumSslStream> {
367    /// Creates a new SSL client and tries to connect to `socket_addr`. Optionally, if
368    /// `validate_domain` is `true`, validate the server's certificate.
369    pub fn new_ssl<A: ToSocketAddrsDomain + Clone>(
370        socket_addrs: A,
371        validate_domain: bool,
372        timeout: Option<Duration>,
373    ) -> Result<Self, Error> {
374        debug!(
375            "new_ssl socket_addrs.domain():{:?} validate_domain:{} timeout:{:?}",
376            socket_addrs.domain(),
377            validate_domain,
378            timeout
379        );
380        if validate_domain {
381            socket_addrs.domain().ok_or(Error::MissingDomain)?;
382        }
383        match timeout {
384            Some(timeout) => {
385                let stream = connect_with_total_timeout(socket_addrs.clone(), timeout)?;
386                stream.set_read_timeout(Some(timeout))?;
387                stream.set_write_timeout(Some(timeout))?;
388                Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
389            }
390            None => {
391                let stream = TcpStream::connect(socket_addrs.clone())?;
392                Self::new_ssl_from_stream(socket_addrs, validate_domain, stream)
393            }
394        }
395    }
396
397    /// Create a new SSL client using an existing TcpStream
398    pub fn new_ssl_from_stream<A: ToSocketAddrsDomain>(
399        socket_addr: A,
400        validate_domain: bool,
401        tcp_stream: TcpStream,
402    ) -> Result<Self, Error> {
403        use std::convert::TryFrom;
404
405        if rustls::crypto::CryptoProvider::get_default().is_none() {
406            // We install a crypto provider depending on the set feature.
407            #[cfg(all(feature = "use-rustls", not(feature = "use-rustls-ring")))]
408            rustls::crypto::CryptoProvider::install_default(
409                rustls::crypto::aws_lc_rs::default_provider(),
410            )
411            .map_err(|_| {
412                Error::CouldNotCreateConnection(rustls::Error::General(
413                    "Failed to install CryptoProvider".to_string(),
414                ))
415            })?;
416
417            #[cfg(feature = "use-rustls-ring")]
418            rustls::crypto::CryptoProvider::install_default(
419                rustls::crypto::ring::default_provider(),
420            )
421            .map_err(|_| {
422                Error::CouldNotCreateConnection(rustls::Error::General(
423                    "Failed to install CryptoProvider".to_string(),
424                ))
425            })?;
426        }
427
428        let builder = ClientConfig::builder();
429
430        let config = if validate_domain {
431            socket_addr.domain().ok_or(Error::MissingDomain)?;
432
433            let store = RootCertStore {
434                roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
435            };
436
437            // TODO: cert pinning
438            builder.with_root_certificates(store).with_no_client_auth()
439        } else {
440            builder
441                .dangerous()
442                .with_custom_certificate_verifier(std::sync::Arc::new(
443                    #[cfg(all(feature = "use-rustls", not(feature = "use-rustls-ring")))]
444                    danger::NoCertificateVerification::new(rustls::crypto::aws_lc_rs::default_provider()),
445                    #[cfg(feature = "use-rustls-ring")]
446                    danger::NoCertificateVerification::new(rustls::crypto::ring::default_provider()),
447                ))
448                .with_no_client_auth()
449        };
450
451        let domain = socket_addr.domain().unwrap_or("NONE").to_string();
452        let session = ClientConnection::new(
453            std::sync::Arc::new(config),
454            ServerName::try_from(domain.clone())
455                .map_err(|_| Error::InvalidDNSNameError(domain.clone()))?,
456        )
457        .map_err(Error::CouldNotCreateConnection)?;
458        let stream = StreamOwned::new(session, tcp_stream);
459
460        Ok(stream.into())
461    }
462}
463
464#[cfg(any(feature = "default", feature = "proxy"))]
465/// Transport type used to establish a connection to a server through a socks proxy
466pub type ElectrumProxyStream = Socks5Stream;
467#[cfg(any(feature = "default", feature = "proxy"))]
468impl RawClient<ElectrumProxyStream> {
469    /// Creates a new socks client and tries to connect to `target_addr` using `proxy_addr` as a
470    /// socks proxy server. The DNS resolution of `target_addr`, if required, is done
471    /// through the proxy. This allows to specify, for instance, `.onion` addresses.
472    pub fn new_proxy<T: ToTargetAddr>(
473        target_addr: T,
474        proxy: &crate::Socks5Config,
475        timeout: Option<Duration>,
476    ) -> Result<Self, Error> {
477        let mut stream = match proxy.credentials.as_ref() {
478            Some(cred) => Socks5Stream::connect_with_password(
479                &proxy.addr,
480                target_addr,
481                &cred.username,
482                &cred.password,
483                timeout,
484            )?,
485            None => Socks5Stream::connect(&proxy.addr, target_addr, timeout)?,
486        };
487        stream.get_mut().set_read_timeout(timeout)?;
488        stream.get_mut().set_write_timeout(timeout)?;
489
490        Ok(stream.into())
491    }
492
493    #[cfg(any(
494        feature = "use-openssl",
495        feature = "use-rustls",
496        feature = "use-rustls-ring"
497    ))]
498    /// Creates a new TLS client that connects to `target_addr` using `proxy_addr` as a socks proxy
499    /// server. The DNS resolution of `target_addr`, if required, is done through the proxy. This
500    /// allows to specify, for instance, `.onion` addresses.
501    pub fn new_proxy_ssl<T: ToTargetAddr>(
502        target_addr: T,
503        validate_domain: bool,
504        proxy: &crate::Socks5Config,
505        timeout: Option<Duration>,
506    ) -> Result<RawClient<ElectrumSslStream>, Error> {
507        let target = target_addr.to_target_addr()?;
508
509        let mut stream = match proxy.credentials.as_ref() {
510            Some(cred) => Socks5Stream::connect_with_password(
511                &proxy.addr,
512                target_addr,
513                &cred.username,
514                &cred.password,
515                timeout,
516            )?,
517            None => Socks5Stream::connect(&proxy.addr, target.clone(), timeout)?,
518        };
519        stream.get_mut().set_read_timeout(timeout)?;
520        stream.get_mut().set_write_timeout(timeout)?;
521
522        RawClient::new_ssl_from_stream(target, validate_domain, stream.into_inner())
523    }
524}
525
526#[derive(Debug)]
527enum ChannelMessage {
528    Response(serde_json::Value),
529    WakeUp,
530    Error(Arc<std::io::Error>),
531}
532
533impl<S: Read + Write> RawClient<S> {
534    // TODO: to enable this we have to find a way to allow concurrent read and writes to the
535    // underlying transport struct. This can be done pretty easily for TcpStream because it can be
536    // split into a "read" and a "write" object, but it's not as trivial for other types. Without
537    // such thing, this causes a deadlock, because the reader thread takes a lock on the
538    // `ClonableStream` before other threads can send a request to the server. They will block
539    // waiting for the reader to release the mutex, but this will never happen because the server
540    // didn't receive any request, so it has nothing to send back.
541    // pub fn reader_thread(&self) -> Result<(), Error> {
542    //     self._reader_thread(None).map(|_| ())
543    // }
544
545    fn _reader_thread(&self, until_message: Option<usize>) -> Result<serde_json::Value, Error> {
546        let mut raw_resp = String::new();
547        let resp = match self.buf_reader.try_lock() {
548            Ok(mut reader) => {
549                trace!(
550                    "Starting reader thread with `until_message` = {:?}",
551                    until_message
552                );
553
554                if let Some(until_message) = until_message {
555                    // If we are trying to start a reader thread but the corresponding sender is
556                    // missing from the map, exit immediately. We might have already received a
557                    // response for that id, but we don't know it yet. Exiting here forces the
558                    // calling code to fallback to the sender-receiver method, and it should find
559                    // a message there waiting for it.
560                    if self.waiting_map.lock()?.get(&until_message).is_none() {
561                        return Err(Error::CouldntLockReader);
562                    }
563                }
564
565                // Loop over every message
566                loop {
567                    raw_resp.clear();
568
569                    if let Err(e) = reader.read_line(&mut raw_resp) {
570                        let error = Arc::new(e);
571                        for (_, s) in self.waiting_map.lock().unwrap().drain() {
572                            s.send(ChannelMessage::Error(error.clone()))?;
573                        }
574                        return Err(Error::SharedIOError(error));
575                    }
576                    trace!("<== {}", raw_resp);
577
578                    let resp: serde_json::Value = serde_json::from_str(&raw_resp)?;
579
580                    // Normally there is and id, but it's missing for spontaneous notifications
581                    // from the server
582                    let resp_id = resp["id"]
583                        .as_str()
584                        .and_then(|s| s.parse().ok())
585                        .or_else(|| resp["id"].as_u64().map(|i| i as usize));
586                    match resp_id {
587                        Some(resp_id) if until_message == Some(resp_id) => {
588                            // We have a valid id and it's exactly the one we were waiting for!
589                            trace!(
590                                "Reader thread {} received a response for its request",
591                                resp_id
592                            );
593
594                            // Remove ourselves from the "waiting map"
595                            let mut map = self.waiting_map.lock()?;
596                            map.remove(&resp_id);
597
598                            // If the map is not empty, we select a random thread to become the
599                            // new reader thread.
600                            if let Some(err) = map.values().find_map(|sender| {
601                                sender
602                                    .send(ChannelMessage::WakeUp)
603                                    .map_err(|err| {
604                                        warn!("Unable to wake up a thread, trying some other");
605                                        err
606                                    })
607                                    .err()
608                            }) {
609                                error!("All the threads has failed, giving up");
610                                return Err(err)?;
611                            }
612
613                            break Ok(resp);
614                        }
615                        Some(resp_id) => {
616                            // We have an id, but it's not our response. Notify the thread and
617                            // move on
618                            trace!("Reader thread received response for {}", resp_id);
619
620                            if let Some(sender) = self.waiting_map.lock()?.remove(&resp_id) {
621                                sender.send(ChannelMessage::Response(resp))?;
622                            } else {
623                                warn!("Missing listener for {}", resp_id);
624                            }
625                        }
626                        None => {
627                            // No id, that's probably a notification.
628                            let mut resp = resp;
629
630                            if let Some(method) = resp["method"].take().as_str() {
631                                self.handle_notification(method, resp["params"].take())?;
632                            } else {
633                                warn!("Unexpected response: {:?}", resp);
634                            }
635                        }
636                    }
637                }
638            }
639            Err(TryLockError::WouldBlock) => {
640                // If we "WouldBlock" here it means that there's already a reader thread
641                // running somewhere.
642                Err(Error::CouldntLockReader)
643            }
644            Err(TryLockError::Poisoned(e)) => Err(e)?,
645        };
646
647        let resp = resp?;
648        if let Some(err) = resp.get("error") {
649            Err(Error::Protocol(err.clone()))
650        } else {
651            Ok(resp)
652        }
653    }
654
655    fn call(&self, req: Request) -> Result<serde_json::Value, Error> {
656        // Add our listener to the map before we send the request, to make sure we don't get a
657        // reply before the receiver is added
658        let (sender, receiver) = channel();
659        self.waiting_map.lock()?.insert(req.id, sender);
660
661        let mut raw = serde_json::to_vec(&req)?;
662        trace!("==> {}", String::from_utf8_lossy(&raw));
663
664        raw.extend_from_slice(b"\n");
665        let mut stream = self.stream.lock()?;
666        stream.write_all(&raw)?;
667        stream.flush()?;
668        drop(stream); // release the lock
669
670        self.increment_calls();
671
672        let mut resp = match self.recv(&receiver, req.id) {
673            Ok(resp) => resp,
674            e @ Err(_) => {
675                // In case of error our sender could still be left in the map, depending on where
676                // the error happened. Just in case, try to remove it here
677                self.waiting_map.lock()?.remove(&req.id);
678                return e;
679            }
680        };
681        Ok(resp["result"].take())
682    }
683
684    fn recv(
685        &self,
686        receiver: &Receiver<ChannelMessage>,
687        req_id: usize,
688    ) -> Result<serde_json::Value, Error> {
689        loop {
690            // Try to take the lock on the reader. If we manage to do so, we'll become the reader
691            // thread until we get our reponse
692            match self._reader_thread(Some(req_id)) {
693                Ok(response) => break Ok(response),
694                Err(Error::CouldntLockReader) => {
695                    match receiver.recv()? {
696                        // Received our response, returning it
697                        ChannelMessage::Response(received) => break Ok(received),
698                        ChannelMessage::WakeUp => {
699                            // We have been woken up, this means that we should try becoming the
700                            // reader thread ourselves
701                            trace!("WakeUp for {}", req_id);
702
703                            continue;
704                        }
705                        ChannelMessage::Error(e) => {
706                            warn!("Received ChannelMessage::Error");
707
708                            break Err(Error::SharedIOError(e));
709                        }
710                    }
711                }
712                e @ Err(_) => break e,
713            }
714        }
715    }
716
717    fn handle_notification(&self, method: &str, result: serde_json::Value) -> Result<(), Error> {
718        match method {
719            "blockchain.headers.subscribe" => self.headers.lock()?.append(
720                &mut serde_json::from_value::<Vec<RawHeaderNotification>>(result)?
721                    .into_iter()
722                    .collect(),
723            ),
724            "blockchain.scripthash.subscribe" => {
725                let unserialized: ScriptNotification = serde_json::from_value(result)?;
726                let mut script_notifications = self.script_notifications.lock()?;
727
728                let queue = script_notifications
729                    .get_mut(&unserialized.scripthash)
730                    .ok_or(Error::NotSubscribed(unserialized.scripthash))?;
731
732                queue.push_back(unserialized.status);
733            }
734            _ => info!("received unknown notification for method `{}`", method),
735        }
736
737        Ok(())
738    }
739
740    pub(crate) fn internal_raw_call_with_vec(
741        &self,
742        method_name: &str,
743        params: Vec<Param>,
744    ) -> Result<serde_json::Value, Error> {
745        let req = Request::new_id(
746            self.last_id.fetch_add(1, Ordering::SeqCst),
747            method_name,
748            params,
749        );
750        let result = self.call(req)?;
751
752        Ok(result)
753    }
754
755    #[inline]
756    #[cfg(feature = "debug-calls")]
757    fn increment_calls(&self) {
758        self.calls.fetch_add(1, Ordering::SeqCst);
759    }
760
761    #[inline]
762    #[cfg(not(feature = "debug-calls"))]
763    fn increment_calls(&self) {}
764}
765
766impl<T: Read + Write> ElectrumApi for RawClient<T> {
767    fn raw_call(
768        &self,
769        method_name: &str,
770        params: impl IntoIterator<Item = Param>,
771    ) -> Result<serde_json::Value, Error> {
772        self.internal_raw_call_with_vec(method_name, params.into_iter().collect())
773    }
774
775    fn batch_call(&self, batch: &Batch) -> Result<Vec<serde_json::Value>, Error> {
776        let mut raw = Vec::new();
777
778        let mut missing_responses = Vec::new();
779        let mut answers = BTreeMap::new();
780
781        // Add our listener to the map before we send the request
782
783        for (method, params) in batch.iter() {
784            let req = Request::new_id(
785                self.last_id.fetch_add(1, Ordering::SeqCst),
786                method,
787                params.to_vec(),
788            );
789            // Add distinct channel to each request so when we remove our request id (and sender) from the waiting_map
790            // we can be sure that the response gets sent to the correct channel in self.recv
791            let (sender, receiver) = channel();
792            missing_responses.push((req.id, receiver));
793
794            self.waiting_map.lock()?.insert(req.id, sender);
795
796            raw.append(&mut serde_json::to_vec(&req)?);
797            raw.extend_from_slice(b"\n");
798        }
799
800        if missing_responses.is_empty() {
801            return Ok(vec![]);
802        }
803
804        trace!("==> {}", String::from_utf8_lossy(&raw));
805
806        let mut stream = self.stream.lock()?;
807        stream.write_all(&raw)?;
808        stream.flush()?;
809        drop(stream); // release the lock
810
811        self.increment_calls();
812
813        for (req_id, receiver) in missing_responses.iter() {
814            match self.recv(receiver, *req_id) {
815                Ok(mut resp) => answers.insert(req_id, resp["result"].take()),
816                Err(e) => {
817                    // In case of error our sender could still be left in the map, depending on where
818                    // the error happened. Just in case, try to remove it here
819                    warn!("got error for req_id {}: {:?}", req_id, e);
820                    warn!("removing all waiting req of this batch");
821                    let mut guard = self.waiting_map.lock()?;
822                    for (req_id, _) in missing_responses.iter() {
823                        guard.remove(req_id);
824                    }
825                    return Err(e);
826                }
827            };
828        }
829
830        Ok(answers.into_values().collect())
831    }
832
833    fn block_headers_subscribe_raw(&self) -> Result<RawHeaderNotification, Error> {
834        let req = Request::new_id(
835            self.last_id.fetch_add(1, Ordering::SeqCst),
836            "blockchain.headers.subscribe",
837            vec![],
838        );
839        let value = self.call(req)?;
840
841        Ok(serde_json::from_value(value)?)
842    }
843
844    fn block_headers_pop_raw(&self) -> Result<Option<RawHeaderNotification>, Error> {
845        Ok(self.headers.lock()?.pop_front())
846    }
847
848    fn block_header_raw(&self, height: usize) -> Result<Vec<u8>, Error> {
849        let req = Request::new_id(
850            self.last_id.fetch_add(1, Ordering::SeqCst),
851            "blockchain.block.header",
852            vec![Param::Usize(height)],
853        );
854        let result = self.call(req)?;
855
856        Ok(Vec::<u8>::from_hex(
857            result
858                .as_str()
859                .ok_or_else(|| Error::InvalidResponse(result.clone()))?,
860        )?)
861    }
862
863    fn block_headers(&self, start_height: usize, count: usize) -> Result<GetHeadersRes, Error> {
864        let req = Request::new_id(
865            self.last_id.fetch_add(1, Ordering::SeqCst),
866            "blockchain.block.headers",
867            vec![Param::Usize(start_height), Param::Usize(count)],
868        );
869        let result = self.call(req)?;
870
871        let mut deserialized: GetHeadersRes = serde_json::from_value(result)?;
872        for i in 0..deserialized.count {
873            let (start, end) = (i * 80, (i + 1) * 80);
874            deserialized
875                .headers
876                .push(deserialize(&deserialized.raw_headers[start..end])?);
877        }
878        deserialized.raw_headers.clear();
879
880        Ok(deserialized)
881    }
882
883    fn estimate_fee(&self, number: usize) -> Result<f64, Error> {
884        let req = Request::new_id(
885            self.last_id.fetch_add(1, Ordering::SeqCst),
886            "blockchain.estimatefee",
887            vec![Param::Usize(number)],
888        );
889        let result = self.call(req)?;
890
891        result
892            .as_f64()
893            .ok_or_else(|| Error::InvalidResponse(result.clone()))
894    }
895
896    fn relay_fee(&self) -> Result<f64, Error> {
897        let req = Request::new_id(
898            self.last_id.fetch_add(1, Ordering::SeqCst),
899            "blockchain.relayfee",
900            vec![],
901        );
902        let result = self.call(req)?;
903
904        result
905            .as_f64()
906            .ok_or_else(|| Error::InvalidResponse(result.clone()))
907    }
908
909    fn script_subscribe(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
910        let script_hash = script.to_electrum_scripthash();
911        let mut script_notifications = self.script_notifications.lock()?;
912
913        if script_notifications.contains_key(&script_hash) {
914            return Err(Error::AlreadySubscribed(script_hash));
915        }
916
917        script_notifications.insert(script_hash, VecDeque::new());
918        drop(script_notifications);
919
920        let req = Request::new_id(
921            self.last_id.fetch_add(1, Ordering::SeqCst),
922            "blockchain.scripthash.subscribe",
923            vec![Param::String(script_hash.to_hex())],
924        );
925        let value = self.call(req)?;
926
927        Ok(serde_json::from_value(value)?)
928    }
929
930    fn batch_script_subscribe<'s, I>(&self, scripts: I) -> Result<Vec<Option<ScriptStatus>>, Error>
931    where
932        I: IntoIterator + Clone,
933        I::Item: Borrow<&'s Script>,
934    {
935        {
936            let mut script_notifications = self.script_notifications.lock()?;
937
938            for script in scripts.clone() {
939                let script_hash = script.borrow().to_electrum_scripthash();
940                if script_notifications.contains_key(&script_hash) {
941                    return Err(Error::AlreadySubscribed(script_hash));
942                }
943                script_notifications.insert(script_hash, VecDeque::new());
944            }
945        }
946        impl_batch_call!(self, scripts, script_subscribe)
947    }
948
949    fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
950        let script_hash = script.to_electrum_scripthash();
951        let mut script_notifications = self.script_notifications.lock()?;
952
953        if !script_notifications.contains_key(&script_hash) {
954            return Err(Error::NotSubscribed(script_hash));
955        }
956
957        let req = Request::new_id(
958            self.last_id.fetch_add(1, Ordering::SeqCst),
959            "blockchain.scripthash.unsubscribe",
960            vec![Param::String(script_hash.to_hex())],
961        );
962        let value = self.call(req)?;
963        let answer = serde_json::from_value(value)?;
964
965        script_notifications.remove(&script_hash);
966
967        Ok(answer)
968    }
969
970    fn script_pop(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
971        let script_hash = script.to_electrum_scripthash();
972
973        match self.script_notifications.lock()?.get_mut(&script_hash) {
974            None => Err(Error::NotSubscribed(script_hash)),
975            Some(queue) => Ok(queue.pop_front()),
976        }
977    }
978
979    fn script_get_balance(&self, script: &Script) -> Result<GetBalanceRes, Error> {
980        let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
981        let req = Request::new_id(
982            self.last_id.fetch_add(1, Ordering::SeqCst),
983            "blockchain.scripthash.get_balance",
984            params,
985        );
986        let result = self.call(req)?;
987
988        Ok(serde_json::from_value(result)?)
989    }
990    fn batch_script_get_balance<'s, I>(&self, scripts: I) -> Result<Vec<GetBalanceRes>, Error>
991    where
992        I: IntoIterator + Clone,
993        I::Item: Borrow<&'s Script>,
994    {
995        impl_batch_call!(self, scripts, script_get_balance)
996    }
997
998    fn script_get_history(&self, script: &Script) -> Result<Vec<GetHistoryRes>, Error> {
999        let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
1000        let req = Request::new_id(
1001            self.last_id.fetch_add(1, Ordering::SeqCst),
1002            "blockchain.scripthash.get_history",
1003            params,
1004        );
1005        let result = self.call(req)?;
1006
1007        Ok(serde_json::from_value(result)?)
1008    }
1009    fn batch_script_get_history<'s, I>(&self, scripts: I) -> Result<Vec<Vec<GetHistoryRes>>, Error>
1010    where
1011        I: IntoIterator + Clone,
1012        I::Item: Borrow<&'s Script>,
1013    {
1014        impl_batch_call!(self, scripts, script_get_history)
1015    }
1016
1017    fn script_list_unspent(&self, script: &Script) -> Result<Vec<ListUnspentRes>, Error> {
1018        let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
1019        let req = Request::new_id(
1020            self.last_id.fetch_add(1, Ordering::SeqCst),
1021            "blockchain.scripthash.listunspent",
1022            params,
1023        );
1024        let result = self.call(req)?;
1025        let mut result: Vec<ListUnspentRes> = serde_json::from_value(result)?;
1026
1027        // This should not be necessary, since the protocol documentation says that the txs should
1028        // be "in blockchain order" (https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-scripthash-listunspent).
1029        // However, elects seems to be ignoring this at the moment, so we'll sort again here just
1030        // to make sure the result is consistent.
1031        result.sort_unstable_by_key(|k| (k.height, k.tx_pos));
1032        Ok(result)
1033    }
1034
1035    fn batch_script_list_unspent<'s, I>(
1036        &self,
1037        scripts: I,
1038    ) -> Result<Vec<Vec<ListUnspentRes>>, Error>
1039    where
1040        I: IntoIterator + Clone,
1041        I::Item: Borrow<&'s Script>,
1042    {
1043        impl_batch_call!(self, scripts, script_list_unspent)
1044    }
1045
1046    fn transaction_get_raw(&self, txid: &Txid) -> Result<Vec<u8>, Error> {
1047        let params = vec![Param::String(format!("{:x}", txid))];
1048        let req = Request::new_id(
1049            self.last_id.fetch_add(1, Ordering::SeqCst),
1050            "blockchain.transaction.get",
1051            params,
1052        );
1053        let result = self.call(req)?;
1054
1055        Ok(Vec::<u8>::from_hex(
1056            result
1057                .as_str()
1058                .ok_or_else(|| Error::InvalidResponse(result.clone()))?,
1059        )?)
1060    }
1061
1062    fn batch_transaction_get_raw<'t, I>(&self, txids: I) -> Result<Vec<Vec<u8>>, Error>
1063    where
1064        I: IntoIterator + Clone,
1065        I::Item: Borrow<&'t Txid>,
1066    {
1067        let txs_string: Result<Vec<String>, Error> = impl_batch_call!(self, txids, transaction_get);
1068        txs_string?
1069            .iter()
1070            .map(|s| Ok(Vec::<u8>::from_hex(s)?))
1071            .collect()
1072    }
1073
1074    fn batch_block_header_raw<'s, I>(&self, heights: I) -> Result<Vec<Vec<u8>>, Error>
1075    where
1076        I: IntoIterator + Clone,
1077        I::Item: Borrow<u32>,
1078    {
1079        let headers_string: Result<Vec<String>, Error> =
1080            impl_batch_call!(self, heights, block_header, apply_deref);
1081        headers_string?
1082            .iter()
1083            .map(|s| Ok(Vec::<u8>::from_hex(s)?))
1084            .collect()
1085    }
1086
1087    fn batch_estimate_fee<'s, I>(&self, numbers: I) -> Result<Vec<f64>, Error>
1088    where
1089        I: IntoIterator + Clone,
1090        I::Item: Borrow<usize>,
1091    {
1092        impl_batch_call!(self, numbers, estimate_fee, apply_deref)
1093    }
1094
1095    fn transaction_broadcast_raw(&self, raw_tx: &[u8]) -> Result<Txid, Error> {
1096        let params = vec![Param::String(raw_tx.to_lower_hex_string())];
1097        let req = Request::new_id(
1098            self.last_id.fetch_add(1, Ordering::SeqCst),
1099            "blockchain.transaction.broadcast",
1100            params,
1101        );
1102        let result = self.call(req)?;
1103
1104        Ok(serde_json::from_value(result)?)
1105    }
1106
1107    fn transaction_get_merkle(&self, txid: &Txid, height: usize) -> Result<GetMerkleRes, Error> {
1108        let params = vec![Param::String(format!("{:x}", txid)), Param::Usize(height)];
1109        let req = Request::new_id(
1110            self.last_id.fetch_add(1, Ordering::SeqCst),
1111            "blockchain.transaction.get_merkle",
1112            params,
1113        );
1114        let result = self.call(req)?;
1115
1116        Ok(serde_json::from_value(result)?)
1117    }
1118
1119    fn batch_transaction_get_merkle<I>(
1120        &self,
1121        txids_and_heights: I,
1122    ) -> Result<Vec<GetMerkleRes>, Error>
1123    where
1124        I: IntoIterator + Clone,
1125        I::Item: Borrow<(Txid, usize)>,
1126    {
1127        impl_batch_call!(self, txids_and_heights, transaction_get_merkle)
1128    }
1129
1130    fn txid_from_pos(&self, height: usize, tx_pos: usize) -> Result<Txid, Error> {
1131        let params = vec![Param::Usize(height), Param::Usize(tx_pos)];
1132        let req = Request::new_id(
1133            self.last_id.fetch_add(1, Ordering::SeqCst),
1134            "blockchain.transaction.id_from_pos",
1135            params,
1136        );
1137        let result = self.call(req)?;
1138
1139        Ok(serde_json::from_value(result)?)
1140    }
1141
1142    fn txid_from_pos_with_merkle(
1143        &self,
1144        height: usize,
1145        tx_pos: usize,
1146    ) -> Result<TxidFromPosRes, Error> {
1147        let params = vec![
1148            Param::Usize(height),
1149            Param::Usize(tx_pos),
1150            Param::Bool(true),
1151        ];
1152        let req = Request::new_id(
1153            self.last_id.fetch_add(1, Ordering::SeqCst),
1154            "blockchain.transaction.id_from_pos",
1155            params,
1156        );
1157        let result = self.call(req)?;
1158
1159        Ok(serde_json::from_value(result)?)
1160    }
1161
1162    fn server_features(&self) -> Result<ServerFeaturesRes, Error> {
1163        let req = Request::new_id(
1164            self.last_id.fetch_add(1, Ordering::SeqCst),
1165            "server.features",
1166            vec![],
1167        );
1168        let result = self.call(req)?;
1169
1170        Ok(serde_json::from_value(result)?)
1171    }
1172
1173    fn ping(&self) -> Result<(), Error> {
1174        let req = Request::new_id(
1175            self.last_id.fetch_add(1, Ordering::SeqCst),
1176            "server.ping",
1177            vec![],
1178        );
1179        self.call(req)?;
1180
1181        Ok(())
1182    }
1183
1184    #[cfg(feature = "debug-calls")]
1185    fn calls_made(&self) -> Result<usize, Error> {
1186        Ok(self.calls.load(Ordering::SeqCst))
1187    }
1188}
1189
1190#[cfg(test)]
1191mod test {
1192    use std::str::FromStr;
1193
1194    use crate::utils;
1195
1196    use super::RawClient;
1197    use crate::api::ElectrumApi;
1198
1199    fn get_test_server() -> String {
1200        std::env::var("TEST_ELECTRUM_SERVER").unwrap_or("electrum.blockstream.info:50001".into())
1201    }
1202
1203    #[test]
1204    fn test_server_features_simple() {
1205        let client = RawClient::new(get_test_server(), None).unwrap();
1206
1207        let resp = client.server_features().unwrap();
1208        assert_eq!(
1209            resp.genesis_hash,
1210            [
1211                0, 0, 0, 0, 0, 25, 214, 104, 156, 8, 90, 225, 101, 131, 30, 147, 79, 247, 99, 174,
1212                70, 162, 166, 193, 114, 179, 241, 182, 10, 140, 226, 111
1213            ],
1214        );
1215        assert_eq!(resp.hash_function, Some("sha256".into()));
1216        assert_eq!(resp.pruning, None);
1217    }
1218
1219    #[test]
1220    #[ignore = "depends on a live server"]
1221    fn test_batch_response_ordering() {
1222        // The electrum.blockstream.info:50001 node always sends back ordered responses which will make this always pass.
1223        // However, many servers do not, so we use one of those servers for this test.
1224        let client = RawClient::new("exs.dyshek.org:50001", None).unwrap();
1225        let heights: Vec<u32> = vec![1, 4, 8, 12, 222, 6666, 12];
1226        let result_times = [
1227            1231469665, 1231470988, 1231472743, 1231474888, 1231770653, 1236456633, 1231474888,
1228        ];
1229        // Check ordering 10 times. This usually fails within 5 if ordering is incorrect.
1230        for _ in 0..10 {
1231            let results = client.batch_block_header(&heights).unwrap();
1232            for (index, result) in results.iter().enumerate() {
1233                assert_eq!(result_times[index], result.time);
1234            }
1235        }
1236    }
1237
1238    #[test]
1239    fn test_relay_fee() {
1240        let client = RawClient::new(get_test_server(), None).unwrap();
1241
1242        let resp = client.relay_fee().unwrap();
1243        assert!(resp > 0.0);
1244    }
1245
1246    #[test]
1247    fn test_estimate_fee() {
1248        let client = RawClient::new(get_test_server(), None).unwrap();
1249
1250        let resp = client.estimate_fee(10).unwrap();
1251        assert!(resp > 0.0);
1252    }
1253
1254    #[test]
1255    fn test_block_header() {
1256        let client = RawClient::new(get_test_server(), None).unwrap();
1257
1258        let resp = client.block_header(0).unwrap();
1259        assert_eq!(resp.version, bitcoin::block::Version::ONE);
1260        assert_eq!(resp.time, 1231006505);
1261        assert_eq!(resp.nonce, 0x7c2bac1d);
1262    }
1263
1264    #[test]
1265    fn test_block_header_raw() {
1266        let client = RawClient::new(get_test_server(), None).unwrap();
1267
1268        let resp = client.block_header_raw(0).unwrap();
1269        assert_eq!(
1270            resp,
1271            vec![
1272                1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1273                0, 0, 0, 0, 0, 0, 0, 0, 59, 163, 237, 253, 122, 123, 18, 178, 122, 199, 44, 62,
1274                103, 118, 143, 97, 127, 200, 27, 195, 136, 138, 81, 50, 58, 159, 184, 170, 75, 30,
1275                94, 74, 41, 171, 95, 73, 255, 255, 0, 29, 29, 172, 43, 124
1276            ]
1277        );
1278    }
1279
1280    #[test]
1281    fn test_block_headers() {
1282        let client = RawClient::new(get_test_server(), None).unwrap();
1283
1284        let resp = client.block_headers(0, 4).unwrap();
1285        assert_eq!(resp.count, 4);
1286        assert_eq!(resp.max, 2016);
1287        assert_eq!(resp.headers.len(), 4);
1288
1289        assert_eq!(resp.headers[0].time, 1231006505);
1290    }
1291
1292    #[test]
1293    fn test_script_get_balance() {
1294        use std::str::FromStr;
1295
1296        let client = RawClient::new(get_test_server(), None).unwrap();
1297
1298        // Realistically nobody will ever spend from this address, so we can expect the balance to
1299        // increase over time
1300        let addr = bitcoin::Address::from_str("1CounterpartyXXXXXXXXXXXXXXXUWLpVr")
1301            .unwrap()
1302            .assume_checked();
1303        let resp = client.script_get_balance(&addr.script_pubkey()).unwrap();
1304        assert!(resp.confirmed >= 213091301265);
1305    }
1306
1307    #[test]
1308    fn test_script_get_history() {
1309        use std::str::FromStr;
1310
1311        use bitcoin::Txid;
1312
1313        let client = RawClient::new(get_test_server(), None).unwrap();
1314
1315        // Mt.Gox hack address
1316        let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF")
1317            .unwrap()
1318            .assume_checked();
1319        let resp = client.script_get_history(&addr.script_pubkey()).unwrap();
1320
1321        assert!(resp.len() >= 328);
1322        assert_eq!(
1323            resp[0].tx_hash,
1324            Txid::from_str("e67a0550848b7932d7796aeea16ab0e48a5cfe81c4e8cca2c5b03e0416850114")
1325                .unwrap()
1326        );
1327    }
1328
1329    #[test]
1330    fn test_script_list_unspent() {
1331        use bitcoin::Txid;
1332        use std::str::FromStr;
1333
1334        let client = RawClient::new(get_test_server(), None).unwrap();
1335
1336        // Peter todd's sha256 bounty address https://bitcointalk.org/index.php?topic=293382.0
1337        let addr = bitcoin::Address::from_str("35Snmmy3uhaer2gTboc81ayCip4m9DT4ko")
1338            .unwrap()
1339            .assume_checked();
1340        let resp = client.script_list_unspent(&addr.script_pubkey()).unwrap();
1341
1342        assert!(resp.len() >= 9);
1343        let txid = "397f12ee15f8a3d2ab25c0f6bb7d3c64d2038ca056af10dd8251b98ae0f076b0";
1344        let txid = Txid::from_str(txid).unwrap();
1345        let txs: Vec<_> = resp.iter().filter(|e| e.tx_hash == txid).collect();
1346        assert_eq!(txs.len(), 1);
1347        assert_eq!(txs[0].value, 10000000);
1348        assert_eq!(txs[0].height, 257674);
1349        assert_eq!(txs[0].tx_pos, 1);
1350    }
1351
1352    #[test]
1353    fn test_batch_script_list_unspent() {
1354        use std::str::FromStr;
1355
1356        let client = RawClient::new(get_test_server(), None).unwrap();
1357
1358        // Peter todd's sha256 bounty address https://bitcointalk.org/index.php?topic=293382.0
1359        let script_1 = bitcoin::Address::from_str("35Snmmy3uhaer2gTboc81ayCip4m9DT4ko")
1360            .unwrap()
1361            .assume_checked()
1362            .script_pubkey();
1363
1364        let resp = client
1365            .batch_script_list_unspent(vec![script_1.as_script()])
1366            .unwrap();
1367        assert_eq!(resp.len(), 1);
1368        assert!(resp[0].len() >= 9);
1369    }
1370
1371    #[test]
1372    fn test_batch_estimate_fee() {
1373        let client = RawClient::new(get_test_server(), None).unwrap();
1374
1375        let resp = client.batch_estimate_fee(vec![10, 20]).unwrap();
1376        assert_eq!(resp.len(), 2);
1377        assert!(resp[0] > 0.0);
1378        assert!(resp[1] > 0.0);
1379    }
1380
1381    #[test]
1382    fn test_transaction_get() {
1383        use bitcoin::{transaction, Txid};
1384
1385        let client = RawClient::new(get_test_server(), None).unwrap();
1386
1387        let resp = client
1388            .transaction_get(
1389                &Txid::from_str("cc2ca076fd04c2aeed6d02151c447ced3d09be6fb4d4ef36cb5ed4e7a3260566")
1390                    .unwrap(),
1391            )
1392            .unwrap();
1393        assert_eq!(resp.version, transaction::Version::ONE);
1394        assert_eq!(resp.lock_time.to_consensus_u32(), 0);
1395    }
1396
1397    #[test]
1398    fn test_transaction_get_raw() {
1399        use bitcoin::Txid;
1400
1401        let client = RawClient::new(get_test_server(), None).unwrap();
1402
1403        let resp = client
1404            .transaction_get_raw(
1405                &Txid::from_str("cc2ca076fd04c2aeed6d02151c447ced3d09be6fb4d4ef36cb5ed4e7a3260566")
1406                    .unwrap(),
1407            )
1408            .unwrap();
1409        assert_eq!(
1410            resp,
1411            vec![
1412                1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1413                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 84, 3, 240, 156, 9, 27, 77,
1414                105, 110, 101, 100, 32, 98, 121, 32, 65, 110, 116, 80, 111, 111, 108, 49, 49, 57,
1415                174, 0, 111, 32, 7, 77, 101, 40, 250, 190, 109, 109, 42, 177, 148, 141, 80, 179,
1416                217, 145, 226, 160, 130, 29, 247, 67, 88, 237, 156, 37, 83, 175, 0, 199, 166, 31,
1417                151, 119, 28, 160, 172, 238, 16, 110, 4, 0, 0, 0, 0, 0, 0, 0, 203, 236, 0, 128, 36,
1418                97, 249, 5, 255, 255, 255, 255, 3, 84, 206, 172, 42, 0, 0, 0, 0, 25, 118, 169, 20,
1419                17, 219, 228, 140, 198, 182, 23, 249, 198, 173, 175, 77, 158, 213, 246, 37, 177,
1420                199, 203, 89, 136, 172, 0, 0, 0, 0, 0, 0, 0, 0, 38, 106, 36, 170, 33, 169, 237, 46,
1421                87, 139, 206, 44, 166, 198, 188, 147, 89, 55, 115, 69, 216, 233, 133, 221, 95, 144,
1422                199, 132, 33, 255, 166, 239, 165, 235, 96, 66, 142, 105, 140, 0, 0, 0, 0, 0, 0, 0,
1423                0, 38, 106, 36, 185, 225, 27, 109, 47, 98, 29, 126, 195, 244, 90, 94, 202, 137,
1424                211, 234, 106, 41, 76, 223, 58, 4, 46, 151, 48, 9, 88, 68, 112, 161, 41, 22, 17,
1425                30, 44, 170, 1, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1426                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1427            ]
1428        )
1429    }
1430
1431    #[test]
1432    fn test_transaction_get_merkle() {
1433        use bitcoin::Txid;
1434
1435        let client = RawClient::new(get_test_server(), None).unwrap();
1436
1437        let txid =
1438            Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
1439                .unwrap();
1440        let resp = client.transaction_get_merkle(&txid, 630000).unwrap();
1441        assert_eq!(resp.block_height, 630000);
1442        assert_eq!(resp.pos, 68);
1443        assert_eq!(resp.merkle.len(), 12);
1444        assert_eq!(
1445            resp.merkle[0],
1446            [
1447                34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47, 66,
1448                179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25
1449            ]
1450        );
1451
1452        // Check we can verify the merkle proof validity, but fail if we supply wrong data.
1453        let block_header = client.block_header(resp.block_height).unwrap();
1454        assert!(utils::validate_merkle_proof(
1455            &txid,
1456            &block_header.merkle_root,
1457            &resp
1458        ));
1459
1460        let mut fail_resp = resp.clone();
1461        fail_resp.pos = 13;
1462        assert!(!utils::validate_merkle_proof(
1463            &txid,
1464            &block_header.merkle_root,
1465            &fail_resp
1466        ));
1467
1468        let fail_block_header = client.block_header(resp.block_height + 1).unwrap();
1469        assert!(!utils::validate_merkle_proof(
1470            &txid,
1471            &fail_block_header.merkle_root,
1472            &resp
1473        ));
1474    }
1475
1476    #[test]
1477    fn test_batch_transaction_get_merkle() {
1478        use bitcoin::Txid;
1479
1480        struct TestCase {
1481            txid: Txid,
1482            block_height: usize,
1483            exp_pos: usize,
1484            exp_bytes: [u8; 32],
1485        }
1486
1487        let client = RawClient::new(get_test_server(), None).unwrap();
1488
1489        let test_cases: Vec<TestCase> = vec![
1490            TestCase {
1491                txid: Txid::from_str(
1492                    "1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d",
1493                )
1494                .unwrap(),
1495                block_height: 630000,
1496                exp_pos: 68,
1497                exp_bytes: [
1498                    34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47,
1499                    66, 179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25,
1500                ],
1501            },
1502            TestCase {
1503                txid: Txid::from_str(
1504                    "70a8639bc9b743c0610d1231103a2f8e99f4a25670946b91f16c55a5373b37d1",
1505                )
1506                .unwrap(),
1507                block_height: 630001,
1508                exp_pos: 25,
1509                exp_bytes: [
1510                    169, 100, 34, 99, 168, 101, 25, 168, 184, 90, 77, 50, 151, 245, 130, 101, 193,
1511                    229, 136, 128, 63, 110, 241, 19, 242, 59, 184, 137, 245, 249, 188, 110,
1512                ],
1513            },
1514            TestCase {
1515                txid: Txid::from_str(
1516                    "a0db149ace545beabbd87a8d6b20ffd6aa3b5a50e58add49a3d435f898c272cf",
1517                )
1518                .unwrap(),
1519                block_height: 840000,
1520                exp_pos: 0,
1521                exp_bytes: [
1522                    43, 184, 95, 75, 0, 75, 230, 218, 84, 247, 102, 193, 124, 30, 133, 81, 135, 50,
1523                    113, 18, 194, 49, 239, 47, 243, 94, 186, 208, 234, 103, 198, 158,
1524                ],
1525            },
1526        ];
1527
1528        let txids_and_heights: Vec<(Txid, usize)> = test_cases
1529            .iter()
1530            .map(|case| (case.txid, case.block_height))
1531            .collect();
1532
1533        let resp = client
1534            .batch_transaction_get_merkle(&txids_and_heights)
1535            .unwrap();
1536
1537        for (i, (res, test_case)) in resp.iter().zip(test_cases).enumerate() {
1538            assert_eq!(res.block_height, test_case.block_height);
1539            assert_eq!(res.pos, test_case.exp_pos);
1540            assert_eq!(res.merkle.len(), 12);
1541            assert_eq!(res.merkle[0], test_case.exp_bytes);
1542
1543            // Check we can verify the merkle proof validity, but fail if we supply wrong data.
1544            let block_header = client.block_header(res.block_height).unwrap();
1545            assert!(utils::validate_merkle_proof(
1546                &txids_and_heights[i].0,
1547                &block_header.merkle_root,
1548                res
1549            ));
1550
1551            let mut fail_res = res.clone();
1552            fail_res.pos = 13;
1553            assert!(!utils::validate_merkle_proof(
1554                &txids_and_heights[i].0,
1555                &block_header.merkle_root,
1556                &fail_res
1557            ));
1558
1559            let fail_block_header = client.block_header(res.block_height + 1).unwrap();
1560            assert!(!utils::validate_merkle_proof(
1561                &txids_and_heights[i].0,
1562                &fail_block_header.merkle_root,
1563                res
1564            ));
1565        }
1566    }
1567
1568    #[test]
1569    fn test_txid_from_pos() {
1570        use bitcoin::Txid;
1571
1572        let client = RawClient::new(get_test_server(), None).unwrap();
1573
1574        let txid =
1575            Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
1576                .unwrap();
1577        let resp = client.txid_from_pos(630000, 68).unwrap();
1578        assert_eq!(resp, txid);
1579    }
1580
1581    #[test]
1582    fn test_txid_from_pos_with_merkle() {
1583        use bitcoin::Txid;
1584
1585        let client = RawClient::new(get_test_server(), None).unwrap();
1586
1587        let txid =
1588            Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
1589                .unwrap();
1590        let resp = client.txid_from_pos_with_merkle(630000, 68).unwrap();
1591        assert_eq!(resp.tx_hash, txid);
1592        assert_eq!(
1593            resp.merkle[0],
1594            [
1595                34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47, 66,
1596                179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25
1597            ]
1598        );
1599    }
1600
1601    #[test]
1602    fn test_ping() {
1603        let client = RawClient::new(get_test_server(), None).unwrap();
1604        client.ping().unwrap();
1605    }
1606
1607    #[test]
1608    fn test_block_headers_subscribe() {
1609        let client = RawClient::new(get_test_server(), None).unwrap();
1610        let resp = client.block_headers_subscribe().unwrap();
1611
1612        assert!(resp.height >= 639000);
1613    }
1614
1615    #[test]
1616    fn test_script_subscribe() {
1617        use std::str::FromStr;
1618
1619        let client = RawClient::new(get_test_server(), None).unwrap();
1620
1621        // Mt.Gox hack address
1622        let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF")
1623            .unwrap()
1624            .assume_checked();
1625
1626        // Just make sure that the call returns Ok(something)
1627        client.script_subscribe(&addr.script_pubkey()).unwrap();
1628    }
1629
1630    #[test]
1631    fn test_request_after_error() {
1632        let client = RawClient::new(get_test_server(), None).unwrap();
1633
1634        assert!(client.transaction_broadcast_raw(&[0x00]).is_err());
1635        assert!(client.server_features().is_ok());
1636    }
1637
1638    #[test]
1639    fn test_raw_call() {
1640        use crate::types::Param;
1641
1642        let client = RawClient::new(get_test_server(), None).unwrap();
1643
1644        let params = vec![
1645            Param::String(
1646                "cc2ca076fd04c2aeed6d02151c447ced3d09be6fb4d4ef36cb5ed4e7a3260566".to_string(),
1647            ),
1648            Param::Bool(false),
1649        ];
1650
1651        let resp = client
1652            .raw_call("blockchain.transaction.get", params)
1653            .unwrap();
1654
1655        assert_eq!(
1656            resp,
1657            "01000000000101000000000000000000000000000000000000000000000000000\
1658            0000000000000ffffffff5403f09c091b4d696e656420627920416e74506f6f6c3\
1659            13139ae006f20074d6528fabe6d6d2ab1948d50b3d991e2a0821df74358ed9c255\
1660            3af00c7a61f97771ca0acee106e0400000000000000cbec00802461f905fffffff\
1661            f0354ceac2a000000001976a91411dbe48cc6b617f9c6adaf4d9ed5f625b1c7cb5\
1662            988ac0000000000000000266a24aa21a9ed2e578bce2ca6c6bc9359377345d8e98\
1663            5dd5f90c78421ffa6efa5eb60428e698c0000000000000000266a24b9e11b6d2f6\
1664            21d7ec3f45a5eca89d3ea6a294cdf3a042e973009584470a12916111e2caa01200\
1665            000000000000000000000000000000000000000000000000000000000000000000\
1666            00000"
1667        )
1668    }
1669}