1use 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)]
26pub enum Param {
28 U32(u32),
30 Usize(usize),
32 String(String),
34 Bool(bool),
36 Bytes(Vec<u8>),
38 StringVec(Vec<String>),
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum EstimationMode {
48 Conservative,
52 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
65pub(crate) const REDACTED_AUTHORIZATION: &str = "<REDACTED>";
67
68#[derive(Serialize, Clone)]
69pub struct Request<'a> {
71 jsonrpc: &'static str,
72
73 pub id: usize,
75 pub method: &'a str,
77 pub params: Vec<Param>,
79
80 #[serde(skip_serializing_if = "Option::is_none")]
82 authorization: Option<String>,
83}
84
85impl<'a> Request<'a> {
86 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 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 pub fn with_auth(mut self, authorization: Option<String>) -> Self {
107 self.authorization = authorization;
108 self
109 }
110
111 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
148pub type ScriptHash = Hex32Bytes;
151
152pub type ScriptStatus = Hex32Bytes;
155
156pub trait ToElectrumScriptHash {
158 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#[derive(Clone, Debug, Deserialize)]
217pub struct GetHistoryRes {
218 pub height: i32,
221 pub tx_hash: Txid,
223 pub fee: Option<u64>,
225}
226
227#[derive(Clone, Debug, Deserialize)]
229pub struct ListUnspentRes {
230 pub height: usize,
232 pub tx_hash: Txid,
234 pub tx_pos: usize,
236 pub value: u64,
238}
239
240#[derive(Clone, Debug, Deserialize)]
242pub struct ServerFeaturesRes {
243 pub server_version: String,
245 #[serde(deserialize_with = "from_hex")]
247 pub genesis_hash: [u8; 32],
248 pub protocol_min: String,
250 pub protocol_max: String,
252 pub hash_function: Option<String>,
254 pub pruning: Option<i64>,
256}
257
258#[derive(Clone, Debug, Deserialize)]
263#[serde(from = "(String, String)")]
264pub struct ServerVersionRes {
265 pub server_software_version: String,
267 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#[derive(Clone, Debug, Deserialize)]
284pub struct MempoolInfoRes {
285 pub mempoolminfee: f64,
288 pub minrelaytxfee: f64,
290 pub incrementalrelayfee: f64,
293}
294
295#[derive(Clone, Debug, Deserialize)]
299pub(crate) struct GetHeadersResLegacy {
300 pub max: usize,
302 pub count: usize,
304 #[serde(rename(deserialize = "hex"), deserialize_with = "from_hex")]
306 pub raw_headers: Vec<u8>,
307}
308
309#[derive(Clone, Debug, Deserialize)]
311pub struct GetHeadersRes {
312 pub max: usize,
314 pub count: usize,
316 #[serde(default, rename(deserialize = "headers"))]
318 pub(crate) header_hexes: Vec<String>,
319 #[serde(skip)]
321 pub headers: Vec<block::Header>,
322}
323
324#[derive(Clone, Debug, Deserialize)]
326pub struct GetBalanceRes {
327 pub confirmed: u64,
329 pub unconfirmed: i64,
333}
334
335#[derive(Clone, Debug, Deserialize)]
337pub struct GetMerkleRes {
338 pub block_height: usize,
340 pub pos: usize,
342 #[serde(deserialize_with = "from_hex_array")]
344 pub merkle: Vec<[u8; 32]>,
345}
346
347#[derive(Clone, Debug, Deserialize)]
350pub struct TxidFromPosRes {
351 pub tx_hash: Txid,
353 #[serde(deserialize_with = "from_hex_array")]
355 pub merkle: Vec<[u8; 32]>,
356}
357
358#[derive(Clone, Debug, Deserialize)]
360pub struct BroadcastPackageError {
361 pub txid: Txid,
363 pub error: String,
365}
366
367#[derive(Clone, Debug, Deserialize)]
372pub struct BroadcastPackageRes {
373 pub success: bool,
375 #[serde(default)]
378 pub errors: Vec<BroadcastPackageError>,
379}
380
381#[derive(Clone, Debug, Deserialize)]
383pub struct HeaderNotification {
384 pub height: usize,
386 #[serde(rename = "hex", deserialize_with = "from_hex_header")]
388 pub header: block::Header,
389}
390
391#[derive(Clone, Debug, Deserialize)]
393pub struct RawHeaderNotification {
394 pub height: usize,
396 #[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#[derive(Clone, Debug, Deserialize)]
414pub struct ScriptNotification {
415 pub scripthash: ScriptHash,
417 pub status: ScriptStatus,
419}
420
421#[derive(Debug)]
423pub enum Error {
424 IOError(std::io::Error),
426 JSON(serde_json::error::Error),
428 Hex(bitcoin::hex::HexToBytesError),
430 Protocol(serde_json::Value),
432 Bitcoin(bitcoin::consensus::encode::Error),
434 AlreadySubscribed(ScriptHash),
436 NotSubscribed(ScriptHash),
438 InvalidResponse(serde_json::Value),
440 Message(String),
442 InvalidDNSNameError(String),
444 MissingDomain,
446 AllAttemptsErrored(Vec<Error>),
448 SharedIOError(Arc<std::io::Error>),
450
451 CouldntLockReader,
454 Mpsc,
456 #[cfg(any(feature = "rustls", feature = "rustls-ring"))]
457 CouldNotCreateConnection(rustls::Error),
459
460 #[cfg(feature = "openssl")]
461 InvalidSslMethod(openssl::error::ErrorStack),
463 #[cfg(feature = "openssl")]
464 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 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 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 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}