rostrum 14.0.1

An efficient implementation of Electrum Server with token support
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
use log::{debug, info, warn};
use std::{
    collections::HashMap,
    sync::{atomic::AtomicBool, Arc, Mutex},
    time::Duration,
};

use bitcoincash::Network;
use configure_me::toml::from_str;
use electrum_client_netagnostic::Param;
use serde_json::Value;

use crate::{
    config::{default_electrum_port, Config},
    metrics::Metrics,
    rpc::daemon::tcpsslcommunication::extract_hostname_from_cert,
    rpc::parseutil::parse_version_str,
    utilnet::get_global_ip_from_hostname,
};

use crate::{
    chaindef::BlockHash,
    def::{PROTOCOL_HASH_FUNCTION, PROTOCOL_VERSION_MAX, PROTOCOL_VERSION_MIN},
    edition::Edition,
    signal::Waiter,
};

use super::{
    client::ElectrumClient,
    discoverer::PeerDiscoverer,
    peer::{CandidatePeer, ServerPeer},
};
use crate::def::ROSTRUM_VERSION;
use anyhow::{Context, Result};
use std::net::IpAddr;

/**
 * Max number of candidates to consider from a 'server.peers.subscribe' response.
 */
const MAX_CANDIDATES_PER_REQ: usize = 50;

#[derive(Debug, Clone, Serialize)]
pub struct ServerFeatures {
    genesis_hash: BlockHash,
    hash_function: &'static str,
    protocol_max: &'static str,
    protocol_min: &'static str,
    server_version: String,
    hosts: Option<HashMap<String, HashMap<String, Option<u16>>>>,
    pruning: Option<u64>,
    tokens: bool,
    spent_utxo: bool,
    editions: Vec<&'static str>,
}

pub struct PeerAnnouncer {
    features: ServerFeatures,
    /// Thread responsible for announcing us to other server peers
    announce_thread: Mutex<Option<tokio::task::JoinHandle<()>>>,
    announce_thread_kill: Arc<AtomicBool>,
}

fn discover_our_hostname(network: &Network) -> Option<String> {
    if network == &Network::Regtest {
        return Some("localhost".to_string());
    }
    // TODO: Use other electrum servers to find IP, rather than external service.
    info!("Auto-detecting our public IP");
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(5)))
        .build()
        .into();
    let response = agent.get("https://api.ipify.org").call();
    let body = match response {
        Ok(mut response) => response.body_mut().read_to_string().unwrap_or_default(),
        Err(e) => {
            debug!("Failed to request public IP: {e}.");
            String::default()
        }
    };
    let ip: Option<IpAddr> = body.parse().ok();
    if let Some(ip) = ip {
        debug!("Detected public as {}", ip);
        return Some(ip.to_string());
    }
    None
}

async fn select_hostname(config: &Config) -> Option<String> {
    if let Some(ref hostname) = config.announce_hostname {
        if get_global_ip_from_hostname(hostname).await.is_some() {
            info!("discover: Announcing ourselves using hostname {} in --announce-hostname configuration.", hostname);
            return Some(hostname.clone());
        } else {
            warn!("The hostname {} in --announce-hostname configuration is not global routable. Ignoring.", hostname);
        }
    }
    if let Some(cert_file) = &config.ssl_cert_file {
        if let Ok(Some(hostname)) = extract_hostname_from_cert(cert_file).await {
            info!("discover: Announcing ourselves using hostname {} from --ssl-cert-file configuration.", hostname);
            return Some(hostname);
        }
    }
    // Fallback to announcing ourselves using our public IP.
    let ip = discover_our_hostname(&config.network_type);
    if let Some(ip) = ip {
        info!("discover: Announcing ourselves using our public IP {}", ip);
        return Some(ip.to_string());
    }
    warn!("discover: No valid hostname found. Peer announcement disabled.");
    None
}

impl PeerAnnouncer {
    pub async fn new(genesis_hash: BlockHash, config: &Config) -> Self {
        let mut enabled = config.announce;
        let hostname = select_hostname(config).await;

        if hostname.is_none() {
            enabled = false;
        }

        let hosts: Option<HashMap<String, HashMap<String, Option<u16>>>> = if enabled {
            let hostname = hostname.unwrap();

            let tcp_port = if config.tcp {
                Some(config.electrum_rpc_addr.port())
            } else {
                None
            };

            let ssl_port = if config.tcp_ssl {
                Some(config.electrum_rpc_ssl_addr.port())
            } else {
                config.announce_ssl_port
            };

            let ws_port = if config.websocket {
                Some(config.electrum_ws_addr.port())
            } else {
                None
            };

            let wss_port = if config.websocket_ssl {
                Some(config.electrum_ws_ssl_addr.port())
            } else {
                config.announce_wss_port
            };

            let http_port = if config.http {
                Some(config.electrum_http_addr.port())
            } else {
                None
            };

            let https_port = if config.https {
                Some(config.electrum_https_addr.port())
            } else {
                None
            };

            let ports: HashMap<String, Option<u16>> = [
                ("tcp_port".to_string(), tcp_port),
                ("ssl_port".to_string(), ssl_port),
                ("ws_port".to_string(), ws_port),
                ("wss_port".to_string(), wss_port),
                ("http_port".to_string(), http_port),
                ("https_port".to_string(), https_port),
            ]
            .iter()
            .cloned()
            .collect();
            Some([(hostname, ports)].iter().cloned().collect())
        } else {
            None
        };

        let features = ServerFeatures {
            genesis_hash,
            hash_function: PROTOCOL_HASH_FUNCTION,
            protocol_min: PROTOCOL_VERSION_MIN,
            protocol_max: PROTOCOL_VERSION_MAX,
            server_version: format!("Rostrum {ROSTRUM_VERSION}"),
            hosts,
            pruning: None,
            tokens: true,
            spent_utxo: true,
            editions: Edition::supported(),
        };

        let thread_kill = Arc::new(AtomicBool::new(false));

        Self {
            features: features.clone(),
            announce_thread: Mutex::new(None),
            announce_thread_kill: Arc::clone(&thread_kill),
        }
    }

    pub fn server_features(&self) -> &ServerFeatures {
        &self.features
    }

    pub fn server_version(&self) -> &str {
        &self.features.server_version
    }

    pub async fn start_announce_thread(
        &self,
        discoverer: Arc<PeerDiscoverer>,
        config: &Config,
        metrics: &Metrics,
    ) {
        let enabled = config.announce;

        if !enabled {
            info!("discover: Announcer disabled");
            return;
        }

        let announce_requests = metrics.counter_int(prometheus::Opts::new(
            "rostrum_discover_announce_request",
            "How often we announced ourselfs (attempts) to other server peers",
        ));
        let subscribe_requests = metrics.counter_int(prometheus::Opts::new(
            "rostrum_discover_peer_subscribe_request",
            "How often we requested (attempts) good peers from other server peers",
        ));

        let network = config.network_type;
        let thread_kill = Arc::clone(&self.announce_thread_kill);
        let features = self.features.clone();

        let good_ask_interval =
            Duration::from_secs(if network == Network::Regtest { 10 } else { 300 });

        let announce_thread = crate::thread::spawn_task("announce", async move {
            loop {
                if Waiter::wait_or_shutdown(Duration::from_secs(1))
                    .await
                    .is_err()
                {
                    return Ok(());
                }
                if thread_kill.load(std::sync::atomic::Ordering::Relaxed) {
                    return Ok(());
                }
                if let Some(peer) = discoverer.next_announce().await {
                    announce_requests.inc();
                    announce_to_peer(&peer, &features).await;
                    continue;
                }

                // Chill, so we don't flood our good peers with requests
                if Waiter::wait_or_shutdown(good_ask_interval).await.is_err() {
                    return Ok(());
                }

                // Out of peers to announce to. Check if a random good peer knows of new candidates.
                if let Some(peer) = discoverer.random_good().await {
                    subscribe_requests.inc();
                    let candidates = ask_for_candidates(&peer, &network).await;
                    for peer in candidates.into_iter().take(MAX_CANDIDATES_PER_REQ) {
                        discoverer.maybe_add_announce_queue(peer).await;
                    }
                }
            }
        });
        info!("discover: Announce thread started");
        self.announce_thread
            .lock()
            .unwrap()
            .replace(announce_thread);
    }
}

impl Drop for PeerAnnouncer {
    fn drop(&mut self) {
        self.announce_thread_kill
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

/**
 * Connects to a server and attempts to announce ourself.
 */
pub async fn announce_to_peer(peer: &dyn ServerPeer, features: &ServerFeatures) {
    trace!(
        "discover: Announcing ourselfs to {}",
        peer.pretty_hostname()
    );
    let client = match ElectrumClient::connect(peer, super::client::Protocol::ANY).await {
        Ok(s) => s,
        Err(e) => {
            trace!("discover: Failed to announce to peer: {e}");
            return;
        }
    };

    match client
        .call("server.add_peer", vec![Param::Value(json!(features))])
        .await
    {
        Ok(response) => {
            trace!("discover: Success add_peer response: {}", response)
        }
        Err(e) => {
            trace!(
                "discover: Failed to add to peer {}: {}",
                peer.pretty_hostname(),
                e
            );
        }
    };
}

/**
 * Connects to a server and asks it for good candidates.
 */
pub async fn ask_for_candidates(peer: &dyn ServerPeer, network: &Network) -> Vec<CandidatePeer> {
    let client = match ElectrumClient::connect(peer, super::client::Protocol::ANY).await {
        Ok(s) => s,
        Err(e) => {
            trace!(
                "discover: Failed to request peers from {}: {e}",
                peer.pretty_hostname()
            );
            return Vec::default();
        }
    };

    let response = match client.call("server.peers.subscribe", vec![]).await {
        Ok(r) => r,
        Err(e) => {
            trace!(
                "discover: Failed to request peers from {}: {}",
                peer.pretty_hostname(),
                e
            );
            return vec![];
        }
    };

    match parse_candidate_response(response, network) {
        Ok(c) => c,
        Err(e) => {
            trace!("Invalid candidate response: {e}");
            Vec::default()
        }
    }
}

fn parse_candidate_response(result: Value, network: &Network) -> Result<Vec<CandidatePeer>> {
    let peers = result
        .as_array()
        .context("expected array of peers, got something else")?;
    let mut candidates: Vec<CandidatePeer> = Default::default();
    for peer in peers.iter() {
        let ip = peer
            .get(0)
            .context("ip missing")?
            .as_str()
            .context("ip is not a string")?;
        let hostname = peer
            .get(1)
            .context("hostname missing")?
            .as_str()
            .context("hostname is not a string")?;
        let properties = peer
            .get(2)
            .context("peer properties missing")?
            .as_array()
            .context("expected peer properties to be an array")?;
        let ip: IpAddr = match ip.parse() {
            Ok(ip) => ip,
            Err(_) => {
                // Cannot parse IP. Might be onion. Ignore peer.
                continue;
            }
        };

        let mut candidate = CandidatePeer {
            tcp_port: None,
            ssl_port: None,
            ws_port: None,
            wss_port: None,
            hostname: Some(hostname.to_string()),
            ip,
            version: None,
        };
        for p in properties {
            let p = p.as_str().context("peer property was not a string")?;
            match p.chars().next() {
                Some('t') => {
                    candidate.tcp_port = match from_str(&p[1..]) {
                        Ok(port) => Some(port),
                        Err(_) => {
                            // It's OK not to provide a port number. In this case it's the default port.
                            default_electrum_port(network)
                        }
                    };
                }
                Some('s') => {
                    candidate.ssl_port = match from_str(&p[1..]) {
                        Ok(port) => Some(port),
                        Err(_) => {
                            // It's OK not to provide a port number. In this case it's the default port.
                            // Hack: Assume +1 is the SSL port for all networks
                            default_electrum_port(network).and_then(|p| p.checked_add(1))
                        }
                    };
                }
                Some('v') => {
                    candidate.version = match parse_version_str(&p[1..]) {
                        Some(v) => Some(v),
                        None => {
                            trace!("invalid version string for candidate {}", ip);
                            continue;
                        }
                    }
                }
                _ => { /* ignore property */ }
            }
        }
        candidates.push(candidate);
    }

    Ok(candidates)
}