electrum-client 0.25.0

Bitcoin Electrum client library. Supports plaintext, TLS and Onion servers.
Documentation
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Return types
//!
//! This module contains definitions of all the complex data structures that are returned by calls

use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
use std::ops::Deref;
use std::sync::Arc;

use bitcoin::blockdata::block;
use bitcoin::consensus::encode::deserialize;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::hex::{DisplayHex, FromHex};
use bitcoin::{Script, Txid};

use serde::{de, Deserialize, Serialize};

static JSONRPC_2_0: &str = "2.0";

pub(crate) type Call = (String, Vec<Param>);

#[derive(Serialize, Clone)]
#[serde(untagged)]
/// A single parameter of a [`Request`](struct.Request.html)
pub enum Param {
    /// Integer parameter
    U32(u32),
    /// Integer parameter
    Usize(usize),
    /// String parameter
    String(String),
    /// Boolean parameter
    Bool(bool),
    /// Bytes array parameter
    Bytes(Vec<u8>),
    /// String array parameter
    StringVec(Vec<String>),
}

/// Fee estimation mode for [`estimate_fee`](../api/trait.ElectrumApi.html#method.estimate_fee).
///
/// This parameter was added in protocol v1.6 and is passed to bitcoind's
/// `estimatesmartfee` RPC as the `estimate_mode` parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EstimationMode {
    /// A conservative estimate potentially returns a higher feerate and is more likely to be
    /// sufficient for the desired target, but is not as responsive to short term drops in the
    /// prevailing fee market.
    Conservative,
    /// Economical fee estimate - potentially lower fees but may take longer to confirm.
    Economical,
}

impl Display for EstimationMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            EstimationMode::Conservative => write!(f, "CONSERVATIVE"),
            EstimationMode::Economical => write!(f, "ECONOMICAL"),
        }
    }
}

#[derive(Serialize, Clone)]
/// A request that can be sent to the server
pub struct Request<'a> {
    jsonrpc: &'static str,

    /// The JSON-RPC request id
    pub id: usize,
    /// The request method
    pub method: &'a str,
    /// The request parameters
    pub params: Vec<Param>,

    /// Authorization token (e.g. `"Bearer <token>"`) included in the JSON-RPC request, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    authorization: Option<String>,
}

impl<'a> Request<'a> {
    /// Creates a new [`Request`] with a default `id`.
    fn new(method: &'a str, params: Vec<Param>) -> Self {
        Self {
            id: 0,
            jsonrpc: JSONRPC_2_0,
            method,
            params,
            authorization: None,
        }
    }

    /// Creates a new [`Request`] with a user-specified `id`.
    pub fn new_id(id: usize, method: &'a str, params: Vec<Param>) -> Self {
        let mut instance = Self::new(method, params);
        instance.id = id;

        instance
    }

    /// Sets the `authorization` token for this [`Request`].
    pub fn with_auth(mut self, authorization: Option<String>) -> Self {
        self.authorization = authorization;
        self
    }
}

#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Hex32Bytes(#[serde(deserialize_with = "from_hex", serialize_with = "to_hex")] [u8; 32]);

impl Deref for Hex32Bytes {
    type Target = [u8; 32];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<[u8; 32]> for Hex32Bytes {
    fn from(other: [u8; 32]) -> Hex32Bytes {
        Hex32Bytes(other)
    }
}

impl Hex32Bytes {
    pub(crate) fn to_hex(self) -> String {
        self.0.to_lower_hex_string()
    }
}

/// Format used by the Electrum server to identify an address. The reverse sha256 hash of the
/// scriptPubKey. Documented [here](https://electrumx.readthedocs.io/en/latest/protocol-basics.html#script-hashes).
pub type ScriptHash = Hex32Bytes;

/// Binary blob that condenses all the activity of an address. Used to detect changes without
/// having to compare potentially long lists of transactions.
pub type ScriptStatus = Hex32Bytes;

/// Trait used to convert a struct into the Electrum representation of an address
pub trait ToElectrumScriptHash {
    /// Transforms the current struct into a `ScriptHash`
    fn to_electrum_scripthash(&self) -> ScriptHash;
}

impl ToElectrumScriptHash for Script {
    fn to_electrum_scripthash(&self) -> ScriptHash {
        let mut result = sha256::Hash::hash(self.as_bytes()).to_byte_array();
        result.reverse();

        result.into()
    }
}

fn from_hex<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: FromHex,
    D: de::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    T::from_hex(&s).map_err(de::Error::custom)
}

fn to_hex<S>(bytes: &[u8], serializer: S) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::ser::Serializer,
{
    serializer.serialize_str(&bytes.to_lower_hex_string())
}

fn from_hex_array<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    T: FromHex + std::fmt::Debug,
    D: de::Deserializer<'de>,
{
    let arr = Vec::<String>::deserialize(deserializer)?;

    let results: Vec<Result<T, _>> = arr
        .into_iter()
        .map(|s| T::from_hex(&s).map_err(de::Error::custom))
        .collect();

    let mut answer = Vec::new();
    for x in results.into_iter() {
        answer.push(x?);
    }

    Ok(answer)
}

fn from_hex_header<'de, D>(deserializer: D) -> Result<block::Header, D::Error>
where
    D: de::Deserializer<'de>,
{
    let vec: Vec<u8> = from_hex(deserializer)?;
    deserialize(&vec).map_err(de::Error::custom)
}

/// Response to a [`script_get_history`](../client/struct.Client.html#method.script_get_history) request.
#[derive(Clone, Debug, Deserialize)]
pub struct GetHistoryRes {
    /// Confirmation height of the transaction. 0 if unconfirmed, -1 if unconfirmed while some of
    /// its inputs are unconfirmed too.
    pub height: i32,
    /// Txid of the transaction.
    pub tx_hash: Txid,
    /// Fee of the transaction.
    pub fee: Option<u64>,
}

/// Response to a [`script_list_unspent`](../client/struct.Client.html#method.script_list_unspent) request.
#[derive(Clone, Debug, Deserialize)]
pub struct ListUnspentRes {
    /// Confirmation height of the transaction that created this output.
    pub height: usize,
    /// Txid of the transaction
    pub tx_hash: Txid,
    /// Index of the output in the transaction.
    pub tx_pos: usize,
    /// Value of the output.
    pub value: u64,
}

/// Response to a [`server_features`](../client/struct.Client.html#method.server_features) request.
#[derive(Clone, Debug, Deserialize)]
pub struct ServerFeaturesRes {
    /// Server version reported.
    pub server_version: String,
    /// Hash of the genesis block.
    #[serde(deserialize_with = "from_hex")]
    pub genesis_hash: [u8; 32],
    /// Minimum supported version of the protocol.
    pub protocol_min: String,
    /// Maximum supported version of the protocol.
    pub protocol_max: String,
    /// Hash function used to create the [`ScriptHash`](type.ScriptHash.html).
    pub hash_function: Option<String>,
    /// Pruned height of the server.
    pub pruning: Option<i64>,
}

/// Response to a [`server_version`](../client/struct.Client.html#method.server_version) request.
///
/// This is returned as an array of two strings: `[server_software_version, protocol_version]`.

#[derive(Clone, Debug, Deserialize)]
#[serde(from = "(String, String)")]
pub struct ServerVersionRes {
    /// Server software version string (e.g., "ElectrumX 1.18.0").
    pub server_software_version: String,
    /// Negotiated protocol version (e.g., "1.6").
    pub protocol_version: String,
}

impl From<(String, String)> for ServerVersionRes {
    fn from((server_software_version, protocol_version): (String, String)) -> Self {
        Self {
            server_software_version,
            protocol_version,
        }
    }
}

/// Response to a [`mempool_get_info`](../client/struct.Client.html#method.mempool_get_info) request.
///
/// Contains information about the current state of the mempool.
#[derive(Clone, Debug, Deserialize)]
pub struct MempoolInfoRes {
    /// Dynamic minimum fee rate in BTC/kvB for tx to be accepted given current conditions.
    /// The maximum of `minrelaytxfee` and minimum mempool fee.
    pub mempoolminfee: f64,
    /// Static operator-configurable minimum relay fee for transactions, in BTC/kvB.
    pub minrelaytxfee: f64,
    /// Static operator-configurable minimum fee rate increment for mempool limiting or
    /// replacement, in BTC/kvB.
    pub incrementalrelayfee: f64,
}

/// Response to a [`block_headers`](../client/struct.Client.html#method.block_headers) request (protocol v1.4, legacy format).
///
/// In protocol v1.4, the headers are returned as a single concatenated hex string.
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetHeadersResLegacy {
    /// Maximum number of headers returned in a single response.
    pub max: usize,
    /// Number of headers in this response.
    pub count: usize,
    /// Raw headers concatenated.
    #[serde(rename(deserialize = "hex"), deserialize_with = "from_hex")]
    pub raw_headers: Vec<u8>,
}

/// Response to a [`block_headers`](../client/struct.Client.html#method.block_headers) request.
#[derive(Clone, Debug, Deserialize)]
pub struct GetHeadersRes {
    /// Maximum number of headers returned in a single response.
    pub max: usize,
    /// Number of headers in this response.
    pub count: usize,
    /// Array of header hex strings (v1.6 format).
    #[serde(default, rename(deserialize = "headers"))]
    pub(crate) header_hexes: Vec<String>,
    /// Array of block headers (populated after parsing).
    #[serde(skip)]
    pub headers: Vec<block::Header>,
}

/// Response to a [`script_get_balance`](../client/struct.Client.html#method.script_get_balance) request.
#[derive(Clone, Debug, Deserialize)]
pub struct GetBalanceRes {
    /// Confirmed balance in Satoshis for the address.
    pub confirmed: u64,
    /// Unconfirmed balance in Satoshis for the address.
    ///
    /// Some servers (e.g. `electrs`) return this as a negative value.
    pub unconfirmed: i64,
}

/// Response to a [`transaction_get_merkle`](../client/struct.Client.html#method.transaction_get_merkle) request.
#[derive(Clone, Debug, Deserialize)]
pub struct GetMerkleRes {
    /// Height of the block that confirmed the transaction
    pub block_height: usize,
    /// Position in the block of the transaction.
    pub pos: usize,
    /// The merkle path of the transaction.
    #[serde(deserialize_with = "from_hex_array")]
    pub merkle: Vec<[u8; 32]>,
}

/// Response to a [`txid_from_pos_with_merkle`](../client/struct.Client.html#method.txid_from_pos_with_merkle)
/// request.
#[derive(Clone, Debug, Deserialize)]
pub struct TxidFromPosRes {
    /// Txid of the transaction.
    pub tx_hash: Txid,
    /// The merkle path of the transaction.
    #[serde(deserialize_with = "from_hex_array")]
    pub merkle: Vec<[u8; 32]>,
}

/// Error details for a transaction that failed to broadcast in a package.
#[derive(Clone, Debug, Deserialize)]
pub struct BroadcastPackageError {
    /// The txid of the transaction that failed.
    pub txid: Txid,
    /// The error message describing why the transaction was rejected.
    pub error: String,
}

/// Response to a [`transaction_broadcast_package`](../client/struct.Client.html#method.transaction_broadcast_package)
/// request.
///
/// This method was added in protocol v1.6 for package relay support.
#[derive(Clone, Debug, Deserialize)]
pub struct BroadcastPackageRes {
    /// Whether the package was successfully accepted by the mempool.
    pub success: bool,
    /// List of errors for transactions that were rejected.
    /// Only present if some transactions failed.
    #[serde(default)]
    pub errors: Vec<BroadcastPackageError>,
}

/// Notification of a new block header
#[derive(Clone, Debug, Deserialize)]
pub struct HeaderNotification {
    /// New block height.
    pub height: usize,
    /// Newly added header.
    #[serde(rename = "hex", deserialize_with = "from_hex_header")]
    pub header: block::Header,
}

/// Notification of a new block header with the header encoded as raw bytes
#[derive(Clone, Debug, Deserialize)]
pub struct RawHeaderNotification {
    /// New block height.
    pub height: usize,
    /// Newly added header.
    #[serde(rename = "hex", deserialize_with = "from_hex")]
    pub header: Vec<u8>,
}

impl TryFrom<RawHeaderNotification> for HeaderNotification {
    type Error = Error;

    fn try_from(raw: RawHeaderNotification) -> Result<Self, Self::Error> {
        Ok(HeaderNotification {
            height: raw.height,
            header: deserialize(&raw.header)?,
        })
    }
}

/// Notification of the new status of a script
#[derive(Clone, Debug, Deserialize)]
pub struct ScriptNotification {
    /// Address that generated this notification.
    pub scripthash: ScriptHash,
    /// The new status of the address.
    pub status: ScriptStatus,
}

/// Errors
#[derive(Debug)]
pub enum Error {
    /// Wraps `std::io::Error`
    IOError(std::io::Error),
    /// Wraps `serde_json::error::Error`
    JSON(serde_json::error::Error),
    /// Wraps `bitcoin::hex::HexToBytesError`
    Hex(bitcoin::hex::HexToBytesError),
    /// Error returned by the Electrum server
    Protocol(serde_json::Value),
    /// Error during the deserialization of a Bitcoin data structure
    Bitcoin(bitcoin::consensus::encode::Error),
    /// Already subscribed to the notifications of an address
    AlreadySubscribed(ScriptHash),
    /// Not subscribed to the notifications of an address
    NotSubscribed(ScriptHash),
    /// Error during the deserialization of a response from the server
    InvalidResponse(serde_json::Value),
    /// Generic error with a message
    Message(String),
    /// Invalid domain name for an SSL certificate
    InvalidDNSNameError(String),
    /// Missing domain while it was explicitly asked to validate it
    MissingDomain,
    /// Made one or multiple attempts, always in Error
    AllAttemptsErrored(Vec<Error>),
    /// There was an io error reading the socket, to be shared between threads
    SharedIOError(Arc<std::io::Error>),

    /// Couldn't take a lock on the reader mutex. This means that there's already another reader
    /// thread running
    CouldntLockReader,
    /// Broken IPC communication channel: the other thread probably has exited
    Mpsc,
    #[cfg(any(feature = "rustls", feature = "rustls-ring"))]
    /// Could not create a rustls client connection
    CouldNotCreateConnection(rustls::Error),

    #[cfg(feature = "openssl")]
    /// Invalid OpenSSL method used
    InvalidSslMethod(openssl::error::ErrorStack),
    #[cfg(feature = "openssl")]
    /// SSL Handshake failed with the server
    SslHandshakeError(openssl::ssl::HandshakeError<std::net::TcpStream>),
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Error::IOError(e) => Display::fmt(e, f),
            Error::JSON(e) => Display::fmt(e, f),
            Error::Hex(e) => Display::fmt(e, f),
            Error::Bitcoin(e) => Display::fmt(e, f),
            Error::SharedIOError(e) => Display::fmt(e, f),
            #[cfg(feature = "openssl")]
            Error::SslHandshakeError(e) => Display::fmt(e, f),
            #[cfg(feature = "openssl")]
            Error::InvalidSslMethod(e) => Display::fmt(e, f),
            #[cfg(any(
                feature = "rustls",
                feature = "rustls-ring",
            ))]
            Error::CouldNotCreateConnection(e) => Display::fmt(e, f),

            Error::Message(e) => f.write_str(e),
            Error::InvalidDNSNameError(domain) => write!(f, "Invalid domain name {} not matching SSL certificate", domain),
            Error::AllAttemptsErrored(errors) => {
                f.write_str("Made one or multiple attempts, all errored:\n")?;
                for err in errors {
                    writeln!(f, "\t- {}", err)?;
                }
                Ok(())
            }

            Error::Protocol(e) => write!(f, "Electrum server error: {}", e.clone().take()),
            Error::InvalidResponse(e) => write!(f, "Error during the deserialization of a response from the server: {}", e.clone().take()),

            // TODO: Print out addresses once `ScriptHash` will implement `Display`
            Error::AlreadySubscribed(_) => write!(f, "Already subscribed to the notifications of an address"),
            Error::NotSubscribed(_) => write!(f, "Not subscribed to the notifications of an address"),

            Error::MissingDomain => f.write_str("Missing domain while it was explicitly asked to validate it"),
            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"),
            Error::Mpsc => f.write_str("Broken IPC communication channel: the other thread probably has exited"),
        }
    }
}

impl std::error::Error for Error {}

macro_rules! impl_error {
    ( $from:ty, $to:ident ) => {
        impl std::convert::From<$from> for Error {
            fn from(err: $from) -> Self {
                Error::$to(err.into())
            }
        }
    };
}

impl_error!(std::io::Error, IOError);
impl_error!(serde_json::Error, JSON);
impl_error!(bitcoin::hex::HexToBytesError, Hex);
impl_error!(bitcoin::consensus::encode::Error, Bitcoin);

impl<T> From<std::sync::PoisonError<T>> for Error {
    fn from(_: std::sync::PoisonError<T>) -> Self {
        Error::IOError(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
    }
}

impl<T> From<std::sync::mpsc::SendError<T>> for Error {
    fn from(_: std::sync::mpsc::SendError<T>) -> Self {
        Error::Mpsc
    }
}

impl From<std::sync::mpsc::RecvError> for Error {
    fn from(_: std::sync::mpsc::RecvError) -> Self {
        Error::Mpsc
    }
}

#[cfg(test)]
mod tests {
    use crate::ScriptStatus;

    use super::{Param, Request};

    #[test]
    fn script_status_roundtrip() {
        let script_status: ScriptStatus = [1u8; 32].into();
        let script_status_json = serde_json::to_string(&script_status).unwrap();
        let script_status_back = serde_json::from_str(&script_status_json).unwrap();
        assert_eq!(script_status, script_status_back);
    }

    #[test]
    fn test_request_serialization_without_authorization() {
        let req = Request::new_id(1, "server.version", vec![]);

        let json = serde_json::to_string(&req).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // Authorization field should not be present when None
        assert!(parsed.get("authorization").is_none());
        assert!(!json.contains("authorization"));
        assert_eq!(parsed["jsonrpc"], "2.0");
        assert_eq!(parsed["method"], "server.version");
        assert_eq!(parsed["id"], 1);
    }

    #[test]
    fn test_request_serialization_with_authorization() {
        let mut req = Request::new_id(1, "server.version", vec![]);
        req.authorization = Some("Bearer test-jwt-token".to_string());

        let json = serde_json::to_string(&req).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // Authorization field should be present
        assert_eq!(
            parsed["authorization"],
            serde_json::Value::String("Bearer test-jwt-token".to_string())
        );
        assert_eq!(parsed["jsonrpc"], "2.0");
        assert_eq!(parsed["method"], "server.version");
        assert_eq!(parsed["id"], 1);
    }

    #[test]
    fn test_request_with_params_and_authorization() {
        let mut req = Request::new_id(
            42,
            "blockchain.scripthash.get_balance",
            vec![Param::String("test-scripthash".to_string())],
        );
        req.authorization = Some("Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9".to_string());

        let json = serde_json::to_string(&req).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["id"], 42);
        assert_eq!(parsed["method"], "blockchain.scripthash.get_balance");
        assert_eq!(
            parsed["authorization"],
            "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
        );
        assert!(parsed["params"].is_array());
        assert_eq!(parsed["params"][0], "test-scripthash");
    }
}