Skip to main content

electrum_client/
types.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Return types
4//!
5//! This module contains definitions of all the complex data structures that are returned by calls
6
7use std::convert::TryFrom;
8use std::fmt::{self, Display, Formatter};
9use std::ops::Deref;
10use std::sync::Arc;
11
12use bitcoin::blockdata::block;
13use bitcoin::consensus::encode::deserialize;
14use bitcoin::hashes::{sha256, Hash};
15use bitcoin::hex::{DisplayHex, FromHex};
16use bitcoin::{Script, Txid};
17
18use serde::{de, Deserialize, Serialize};
19
20static JSONRPC_2_0: &str = "2.0";
21
22pub(crate) type Call = (String, Vec<Param>);
23
24#[derive(Serialize, Clone)]
25#[serde(untagged)]
26/// A single parameter of a [`Request`](struct.Request.html)
27pub enum Param {
28    /// Integer parameter
29    U32(u32),
30    /// Integer parameter
31    Usize(usize),
32    /// String parameter
33    String(String),
34    /// Boolean parameter
35    Bool(bool),
36    /// Bytes array parameter
37    Bytes(Vec<u8>),
38    /// String array parameter
39    StringVec(Vec<String>),
40}
41
42/// Fee estimation mode for [`estimate_fee`](../api/trait.ElectrumApi.html#method.estimate_fee).
43///
44/// This parameter was added in protocol v1.6 and is passed to bitcoind's
45/// `estimatesmartfee` RPC as the `estimate_mode` parameter.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum EstimationMode {
48    /// A conservative estimate potentially returns a higher feerate and is more likely to be
49    /// sufficient for the desired target, but is not as responsive to short term drops in the
50    /// prevailing fee market.
51    Conservative,
52    /// Economical fee estimate - potentially lower fees but may take longer to confirm.
53    Economical,
54}
55
56impl Display for EstimationMode {
57    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
58        match self {
59            EstimationMode::Conservative => write!(f, "CONSERVATIVE"),
60            EstimationMode::Economical => write!(f, "ECONOMICAL"),
61        }
62    }
63}
64
65/// Placeholder that replaces the authorization token in log output.
66pub(crate) const REDACTED_AUTHORIZATION: &str = "<REDACTED>";
67
68#[derive(Serialize, Clone)]
69/// A request that can be sent to the server
70pub struct Request<'a> {
71    jsonrpc: &'static str,
72
73    /// The JSON-RPC request id
74    pub id: usize,
75    /// The request method
76    pub method: &'a str,
77    /// The request parameters
78    pub params: Vec<Param>,
79
80    /// Authorization token (e.g. `"Bearer <token>"`) included in the JSON-RPC request, if any.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    authorization: Option<String>,
83}
84
85impl<'a> Request<'a> {
86    /// Creates a new [`Request`] with a default `id`.
87    fn new(method: &'a str, params: Vec<Param>) -> Self {
88        Self {
89            id: 0,
90            jsonrpc: JSONRPC_2_0,
91            method,
92            params,
93            authorization: None,
94        }
95    }
96
97    /// Creates a new [`Request`] with a user-specified `id`.
98    pub fn new_id(id: usize, method: &'a str, params: Vec<Param>) -> Self {
99        let mut instance = Self::new(method, params);
100        instance.id = id;
101
102        instance
103    }
104
105    /// Sets the `authorization` token for this [`Request`].
106    pub fn with_auth(mut self, authorization: Option<String>) -> Self {
107        self.authorization = authorization;
108        self
109    }
110
111    /// Returns a copy of this [`Request`] with the authorization token replaced by
112    /// [`REDACTED_AUTHORIZATION`], safe to log.
113    pub(crate) fn redacted(&self) -> Self {
114        Self {
115            authorization: self
116                .authorization
117                .as_ref()
118                .map(|_| REDACTED_AUTHORIZATION.to_string()),
119            ..self.clone()
120        }
121    }
122}
123
124#[doc(hidden)]
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
126pub struct Hex32Bytes(#[serde(deserialize_with = "from_hex", serialize_with = "to_hex")] [u8; 32]);
127
128impl Deref for Hex32Bytes {
129    type Target = [u8; 32];
130
131    fn deref(&self) -> &Self::Target {
132        &self.0
133    }
134}
135
136impl From<[u8; 32]> for Hex32Bytes {
137    fn from(other: [u8; 32]) -> Hex32Bytes {
138        Hex32Bytes(other)
139    }
140}
141
142impl Hex32Bytes {
143    pub(crate) fn to_hex(self) -> String {
144        self.0.to_lower_hex_string()
145    }
146}
147
148/// Format used by the Electrum server to identify an address. The reverse sha256 hash of the
149/// scriptPubKey. Documented [here](https://electrumx.readthedocs.io/en/latest/protocol-basics.html#script-hashes).
150pub type ScriptHash = Hex32Bytes;
151
152/// Binary blob that condenses all the activity of an address. Used to detect changes without
153/// having to compare potentially long lists of transactions.
154pub type ScriptStatus = Hex32Bytes;
155
156/// Trait used to convert a struct into the Electrum representation of an address
157pub trait ToElectrumScriptHash {
158    /// Transforms the current struct into a `ScriptHash`
159    fn to_electrum_scripthash(&self) -> ScriptHash;
160}
161
162impl ToElectrumScriptHash for Script {
163    fn to_electrum_scripthash(&self) -> ScriptHash {
164        let mut result = sha256::Hash::hash(self.as_bytes()).to_byte_array();
165        result.reverse();
166
167        result.into()
168    }
169}
170
171fn from_hex<'de, T, D>(deserializer: D) -> Result<T, D::Error>
172where
173    T: FromHex,
174    D: de::Deserializer<'de>,
175{
176    let s = String::deserialize(deserializer)?;
177    T::from_hex(&s).map_err(de::Error::custom)
178}
179
180fn to_hex<S>(bytes: &[u8], serializer: S) -> std::result::Result<S::Ok, S::Error>
181where
182    S: serde::ser::Serializer,
183{
184    serializer.serialize_str(&bytes.to_lower_hex_string())
185}
186
187fn from_hex_array<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
188where
189    T: FromHex + std::fmt::Debug,
190    D: de::Deserializer<'de>,
191{
192    let arr = Vec::<String>::deserialize(deserializer)?;
193
194    let results: Vec<Result<T, _>> = arr
195        .into_iter()
196        .map(|s| T::from_hex(&s).map_err(de::Error::custom))
197        .collect();
198
199    let mut answer = Vec::new();
200    for x in results.into_iter() {
201        answer.push(x?);
202    }
203
204    Ok(answer)
205}
206
207fn from_hex_header<'de, D>(deserializer: D) -> Result<block::Header, D::Error>
208where
209    D: de::Deserializer<'de>,
210{
211    let vec: Vec<u8> = from_hex(deserializer)?;
212    deserialize(&vec).map_err(de::Error::custom)
213}
214
215/// Response to a [`script_get_history`](../client/struct.Client.html#method.script_get_history) request.
216#[derive(Clone, Debug, Deserialize)]
217pub struct GetHistoryRes {
218    /// Confirmation height of the transaction. 0 if unconfirmed, -1 if unconfirmed while some of
219    /// its inputs are unconfirmed too.
220    pub height: i32,
221    /// Txid of the transaction.
222    pub tx_hash: Txid,
223    /// Fee of the transaction.
224    pub fee: Option<u64>,
225}
226
227/// Response to a [`script_list_unspent`](../client/struct.Client.html#method.script_list_unspent) request.
228#[derive(Clone, Debug, Deserialize)]
229pub struct ListUnspentRes {
230    /// Confirmation height of the transaction that created this output.
231    pub height: usize,
232    /// Txid of the transaction
233    pub tx_hash: Txid,
234    /// Index of the output in the transaction.
235    pub tx_pos: usize,
236    /// Value of the output.
237    pub value: u64,
238}
239
240/// Response to a [`server_features`](../client/struct.Client.html#method.server_features) request.
241#[derive(Clone, Debug, Deserialize)]
242pub struct ServerFeaturesRes {
243    /// Server version reported.
244    pub server_version: String,
245    /// Hash of the genesis block.
246    #[serde(deserialize_with = "from_hex")]
247    pub genesis_hash: [u8; 32],
248    /// Minimum supported version of the protocol.
249    pub protocol_min: String,
250    /// Maximum supported version of the protocol.
251    pub protocol_max: String,
252    /// Hash function used to create the [`ScriptHash`](type.ScriptHash.html).
253    pub hash_function: Option<String>,
254    /// Pruned height of the server.
255    pub pruning: Option<i64>,
256}
257
258/// Response to a [`server_version`](../client/struct.Client.html#method.server_version) request.
259///
260/// This is returned as an array of two strings: `[server_software_version, protocol_version]`.
261
262#[derive(Clone, Debug, Deserialize)]
263#[serde(from = "(String, String)")]
264pub struct ServerVersionRes {
265    /// Server software version string (e.g., "ElectrumX 1.18.0").
266    pub server_software_version: String,
267    /// Negotiated protocol version (e.g., "1.6").
268    pub protocol_version: String,
269}
270
271impl From<(String, String)> for ServerVersionRes {
272    fn from((server_software_version, protocol_version): (String, String)) -> Self {
273        Self {
274            server_software_version,
275            protocol_version,
276        }
277    }
278}
279
280/// Response to a [`mempool_get_info`](../client/struct.Client.html#method.mempool_get_info) request.
281///
282/// Contains information about the current state of the mempool.
283#[derive(Clone, Debug, Deserialize)]
284pub struct MempoolInfoRes {
285    /// Dynamic minimum fee rate in BTC/kvB for tx to be accepted given current conditions.
286    /// The maximum of `minrelaytxfee` and minimum mempool fee.
287    pub mempoolminfee: f64,
288    /// Static operator-configurable minimum relay fee for transactions, in BTC/kvB.
289    pub minrelaytxfee: f64,
290    /// Static operator-configurable minimum fee rate increment for mempool limiting or
291    /// replacement, in BTC/kvB.
292    pub incrementalrelayfee: f64,
293}
294
295/// Response to a [`block_headers`](../client/struct.Client.html#method.block_headers) request (protocol v1.4, legacy format).
296///
297/// In protocol v1.4, the headers are returned as a single concatenated hex string.
298#[derive(Clone, Debug, Deserialize)]
299pub(crate) struct GetHeadersResLegacy {
300    /// Maximum number of headers returned in a single response.
301    pub max: usize,
302    /// Number of headers in this response.
303    pub count: usize,
304    /// Raw headers concatenated.
305    #[serde(rename(deserialize = "hex"), deserialize_with = "from_hex")]
306    pub raw_headers: Vec<u8>,
307}
308
309/// Response to a [`block_headers`](../client/struct.Client.html#method.block_headers) request.
310#[derive(Clone, Debug, Deserialize)]
311pub struct GetHeadersRes {
312    /// Maximum number of headers returned in a single response.
313    pub max: usize,
314    /// Number of headers in this response.
315    pub count: usize,
316    /// Array of header hex strings (v1.6 format).
317    #[serde(default, rename(deserialize = "headers"))]
318    pub(crate) header_hexes: Vec<String>,
319    /// Array of block headers (populated after parsing).
320    #[serde(skip)]
321    pub headers: Vec<block::Header>,
322}
323
324/// Response to a [`script_get_balance`](../client/struct.Client.html#method.script_get_balance) request.
325#[derive(Clone, Debug, Deserialize)]
326pub struct GetBalanceRes {
327    /// Confirmed balance in Satoshis for the address.
328    pub confirmed: u64,
329    /// Unconfirmed balance in Satoshis for the address.
330    ///
331    /// Some servers (e.g. `electrs`) return this as a negative value.
332    pub unconfirmed: i64,
333}
334
335/// Response to a [`transaction_get_merkle`](../client/struct.Client.html#method.transaction_get_merkle) request.
336#[derive(Clone, Debug, Deserialize)]
337pub struct GetMerkleRes {
338    /// Height of the block that confirmed the transaction
339    pub block_height: usize,
340    /// Position in the block of the transaction.
341    pub pos: usize,
342    /// The merkle path of the transaction.
343    #[serde(deserialize_with = "from_hex_array")]
344    pub merkle: Vec<[u8; 32]>,
345}
346
347/// Response to a [`txid_from_pos_with_merkle`](../client/struct.Client.html#method.txid_from_pos_with_merkle)
348/// request.
349#[derive(Clone, Debug, Deserialize)]
350pub struct TxidFromPosRes {
351    /// Txid of the transaction.
352    pub tx_hash: Txid,
353    /// The merkle path of the transaction.
354    #[serde(deserialize_with = "from_hex_array")]
355    pub merkle: Vec<[u8; 32]>,
356}
357
358/// Error details for a transaction that failed to broadcast in a package.
359#[derive(Clone, Debug, Deserialize)]
360pub struct BroadcastPackageError {
361    /// The txid of the transaction that failed.
362    pub txid: Txid,
363    /// The error message describing why the transaction was rejected.
364    pub error: String,
365}
366
367/// Response to a [`transaction_broadcast_package`](../client/struct.Client.html#method.transaction_broadcast_package)
368/// request.
369///
370/// This method was added in protocol v1.6 for package relay support.
371#[derive(Clone, Debug, Deserialize)]
372pub struct BroadcastPackageRes {
373    /// Whether the package was successfully accepted by the mempool.
374    pub success: bool,
375    /// List of errors for transactions that were rejected.
376    /// Only present if some transactions failed.
377    #[serde(default)]
378    pub errors: Vec<BroadcastPackageError>,
379}
380
381/// Notification of a new block header
382#[derive(Clone, Debug, Deserialize)]
383pub struct HeaderNotification {
384    /// New block height.
385    pub height: usize,
386    /// Newly added header.
387    #[serde(rename = "hex", deserialize_with = "from_hex_header")]
388    pub header: block::Header,
389}
390
391/// Notification of a new block header with the header encoded as raw bytes
392#[derive(Clone, Debug, Deserialize)]
393pub struct RawHeaderNotification {
394    /// New block height.
395    pub height: usize,
396    /// Newly added header.
397    #[serde(rename = "hex", deserialize_with = "from_hex")]
398    pub header: Vec<u8>,
399}
400
401impl TryFrom<RawHeaderNotification> for HeaderNotification {
402    type Error = Error;
403
404    fn try_from(raw: RawHeaderNotification) -> Result<Self, Self::Error> {
405        Ok(HeaderNotification {
406            height: raw.height,
407            header: deserialize(&raw.header)?,
408        })
409    }
410}
411
412/// Notification of the new status of a script
413#[derive(Clone, Debug, Deserialize)]
414pub struct ScriptNotification {
415    /// Address that generated this notification.
416    pub scripthash: ScriptHash,
417    /// The new status of the address.
418    pub status: ScriptStatus,
419}
420
421/// Errors
422#[derive(Debug)]
423pub enum Error {
424    /// Wraps `std::io::Error`
425    IOError(std::io::Error),
426    /// Wraps `serde_json::error::Error`
427    JSON(serde_json::error::Error),
428    /// Wraps `bitcoin::hex::HexToBytesError`
429    Hex(bitcoin::hex::HexToBytesError),
430    /// Error returned by the Electrum server
431    Protocol(serde_json::Value),
432    /// Error during the deserialization of a Bitcoin data structure
433    Bitcoin(bitcoin::consensus::encode::Error),
434    /// Already subscribed to the notifications of an address
435    AlreadySubscribed(ScriptHash),
436    /// Not subscribed to the notifications of an address
437    NotSubscribed(ScriptHash),
438    /// Error during the deserialization of a response from the server
439    InvalidResponse(serde_json::Value),
440    /// Generic error with a message
441    Message(String),
442    /// Invalid domain name for an SSL certificate
443    InvalidDNSNameError(String),
444    /// Missing domain while it was explicitly asked to validate it
445    MissingDomain,
446    /// Made one or multiple attempts, always in Error
447    AllAttemptsErrored(Vec<Error>),
448    /// There was an io error reading the socket, to be shared between threads
449    SharedIOError(Arc<std::io::Error>),
450
451    /// Couldn't take a lock on the reader mutex. This means that there's already another reader
452    /// thread running
453    CouldntLockReader,
454    /// Broken IPC communication channel: the other thread probably has exited
455    Mpsc,
456    #[cfg(any(feature = "rustls", feature = "rustls-ring"))]
457    /// Could not create a rustls client connection
458    CouldNotCreateConnection(rustls::Error),
459
460    #[cfg(feature = "openssl")]
461    /// Invalid OpenSSL method used
462    InvalidSslMethod(openssl::error::ErrorStack),
463    #[cfg(feature = "openssl")]
464    /// SSL Handshake failed with the server
465    SslHandshakeError(openssl::ssl::HandshakeError<std::net::TcpStream>),
466}
467
468impl Display for Error {
469    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
470        match self {
471            Error::IOError(e) => Display::fmt(e, f),
472            Error::JSON(e) => Display::fmt(e, f),
473            Error::Hex(e) => Display::fmt(e, f),
474            Error::Bitcoin(e) => Display::fmt(e, f),
475            Error::SharedIOError(e) => Display::fmt(e, f),
476            #[cfg(feature = "openssl")]
477            Error::SslHandshakeError(e) => Display::fmt(e, f),
478            #[cfg(feature = "openssl")]
479            Error::InvalidSslMethod(e) => Display::fmt(e, f),
480            #[cfg(any(
481                feature = "rustls",
482                feature = "rustls-ring",
483            ))]
484            Error::CouldNotCreateConnection(e) => Display::fmt(e, f),
485
486            Error::Message(e) => f.write_str(e),
487            Error::InvalidDNSNameError(domain) => write!(f, "Invalid domain name {} not matching SSL certificate", domain),
488            Error::AllAttemptsErrored(errors) => {
489                f.write_str("Made one or multiple attempts, all errored:\n")?;
490                for err in errors {
491                    writeln!(f, "\t- {}", err)?;
492                }
493                Ok(())
494            }
495
496            Error::Protocol(e) => write!(f, "Electrum server error: {}", e.clone().take()),
497            Error::InvalidResponse(e) => write!(f, "Error during the deserialization of a response from the server: {}", e.clone().take()),
498
499            // TODO: Print out addresses once `ScriptHash` will implement `Display`
500            Error::AlreadySubscribed(_) => write!(f, "Already subscribed to the notifications of an address"),
501            Error::NotSubscribed(_) => write!(f, "Not subscribed to the notifications of an address"),
502
503            Error::MissingDomain => f.write_str("Missing domain while it was explicitly asked to validate it"),
504            Error::CouldntLockReader => f.write_str("Couldn't take a lock on the reader mutex. This means that there's already another reader thread is running"),
505            Error::Mpsc => f.write_str("Broken IPC communication channel: the other thread probably has exited"),
506        }
507    }
508}
509
510impl std::error::Error for Error {}
511
512macro_rules! impl_error {
513    ( $from:ty, $to:ident ) => {
514        impl std::convert::From<$from> for Error {
515            fn from(err: $from) -> Self {
516                Error::$to(err.into())
517            }
518        }
519    };
520}
521
522impl_error!(std::io::Error, IOError);
523impl_error!(serde_json::Error, JSON);
524impl_error!(bitcoin::hex::HexToBytesError, Hex);
525impl_error!(bitcoin::consensus::encode::Error, Bitcoin);
526
527impl<T> From<std::sync::PoisonError<T>> for Error {
528    fn from(_: std::sync::PoisonError<T>) -> Self {
529        Error::IOError(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
530    }
531}
532
533impl<T> From<std::sync::mpsc::SendError<T>> for Error {
534    fn from(_: std::sync::mpsc::SendError<T>) -> Self {
535        Error::Mpsc
536    }
537}
538
539impl From<std::sync::mpsc::RecvError> for Error {
540    fn from(_: std::sync::mpsc::RecvError) -> Self {
541        Error::Mpsc
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use crate::ScriptStatus;
548
549    use super::{Param, Request, REDACTED_AUTHORIZATION};
550
551    #[test]
552    fn script_status_roundtrip() {
553        let script_status: ScriptStatus = [1u8; 32].into();
554        let script_status_json = serde_json::to_string(&script_status).unwrap();
555        let script_status_back = serde_json::from_str(&script_status_json).unwrap();
556        assert_eq!(script_status, script_status_back);
557    }
558
559    #[test]
560    fn test_request_serialization_without_authorization() {
561        let req = Request::new_id(1, "server.version", vec![]);
562
563        let json = serde_json::to_string(&req).unwrap();
564        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
565
566        // Authorization field should not be present when None
567        assert!(parsed.get("authorization").is_none());
568        assert!(!json.contains("authorization"));
569        assert_eq!(parsed["jsonrpc"], "2.0");
570        assert_eq!(parsed["method"], "server.version");
571        assert_eq!(parsed["id"], 1);
572    }
573
574    #[test]
575    fn test_request_serialization_with_authorization() {
576        let mut req = Request::new_id(1, "server.version", vec![]);
577        req.authorization = Some("Bearer test-jwt-token".to_string());
578
579        let json = serde_json::to_string(&req).unwrap();
580        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
581
582        // Authorization field should be present
583        assert_eq!(
584            parsed["authorization"],
585            serde_json::Value::String("Bearer test-jwt-token".to_string())
586        );
587        assert_eq!(parsed["jsonrpc"], "2.0");
588        assert_eq!(parsed["method"], "server.version");
589        assert_eq!(parsed["id"], 1);
590    }
591
592    #[test]
593    fn test_request_with_params_and_authorization() {
594        let mut req = Request::new_id(
595            42,
596            "blockchain.scripthash.get_balance",
597            vec![Param::String("test-scripthash".to_string())],
598        );
599        req.authorization = Some("Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9".to_string());
600
601        let json = serde_json::to_string(&req).unwrap();
602        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
603
604        assert_eq!(parsed["id"], 42);
605        assert_eq!(parsed["method"], "blockchain.scripthash.get_balance");
606        assert_eq!(
607            parsed["authorization"],
608            "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
609        );
610        assert!(parsed["params"].is_array());
611        assert_eq!(parsed["params"][0], "test-scripthash");
612    }
613
614    #[test]
615    fn test_request_redacted_with_authorization() {
616        let req = Request::new_id(
617            42,
618            "blockchain.scripthash.get_balance",
619            vec![Param::String("test-scripthash".to_string())],
620        )
621        .with_auth(Some("Bearer secret-token".to_string()));
622
623        let json = serde_json::to_string(&req.redacted()).unwrap();
624        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
625
626        assert_eq!(parsed["authorization"], REDACTED_AUTHORIZATION);
627        assert!(!json.contains("secret-token"));
628        assert_eq!(parsed["jsonrpc"], "2.0");
629        assert_eq!(parsed["id"], 42);
630        assert_eq!(parsed["method"], "blockchain.scripthash.get_balance");
631        assert_eq!(parsed["params"][0], "test-scripthash");
632    }
633
634    #[test]
635    fn test_request_redacted_without_authorization() {
636        let req = Request::new_id(1, "server.version", vec![]);
637
638        assert_eq!(
639            serde_json::to_string(&req.redacted()).unwrap(),
640            serde_json::to_string(&req).unwrap()
641        );
642    }
643}