rpc.rs 21.7 KB
Newer Older
1
use bitcoin::blockdata::transaction::Transaction;
2
use bitcoin::consensus::encode::{deserialize, serialize};
3
use bitcoin::util::hash::Sha256dHash;
4
use error_chain::ChainedError;
5
use hex;
6
use serde_json::{from_str, Value};
Roman Zeyde's avatar
Roman Zeyde committed
7
use std::collections::HashMap;
8
use std::io::{BufRead, BufReader, Write};
9
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
10
use std::sync::mpsc::{Sender, SyncSender, TrySendError};
11
use std::sync::{Arc, Mutex};
12
use std::thread;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
13

Roman Zeyde's avatar
Roman Zeyde committed
14 15 16 17
use crate::errors::*;
use crate::metrics::{Gauge, HistogramOpts, HistogramVec, MetricOpts, Metrics};
use crate::query::{Query, Status};
use crate::util::{spawn_thread, Channel, HeaderEntry, SyncChannel};
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
18

Roman Zeyde's avatar
Roman Zeyde committed
19
// TODO: Sha256dHash should be a generic hash-container (since script hash is single SHA256)
Roman Zeyde's avatar
Roman Zeyde committed
20 21
fn hash_from_value(val: Option<&Value>) -> Result<Sha256dHash> {
    let script_hash = val.chain_err(|| "missing hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
22 23 24 25 26
    let script_hash = script_hash.as_str().chain_err(|| "non-string hash")?;
    let script_hash = Sha256dHash::from_hex(script_hash).chain_err(|| "non-hex hash")?;
    Ok(script_hash)
}

27 28 29 30 31 32
fn usize_from_value(val: Option<&Value>, name: &str) -> Result<usize> {
    let val = val.chain_err(|| format!("missing {}", name))?;
    let val = val.as_u64().chain_err(|| format!("non-integer {}", name))?;
    Ok(val as usize)
}

33 34 35 36 37 38 39
fn usize_from_value_or(val: Option<&Value>, name: &str, default: usize) -> Result<usize> {
    if val.is_none() {
        return Ok(default);
    }
    usize_from_value(val, name)
}

40 41 42
fn bool_from_value(val: Option<&Value>, name: &str) -> Result<bool> {
    let val = val.chain_err(|| format!("missing {}", name))?;
    let val = val.as_bool().chain_err(|| format!("not a bool {}", name))?;
43 44 45 46 47 48 49 50
    Ok(val)
}

fn bool_from_value_or(val: Option<&Value>, name: &str, default: bool) -> Result<bool> {
    if val.is_none() {
        return Ok(default);
    }
    bool_from_value(val, name)
51 52
}

53 54 55 56 57
fn unspent_from_status(status: &Status) -> Value {
    json!(Value::Array(
        status
            .unspent()
            .into_iter()
Roman Zeyde's avatar
Roman Zeyde committed
58
            .map(|out| json!({
59 60 61 62
                "height": out.height,
                "tx_pos": out.output_index,
                "tx_hash": out.txn_id.be_hex_string(),
                "value": out.value,
Roman Zeyde's avatar
Roman Zeyde committed
63 64
            }))
            .collect()
65 66 67
    ))
}

68 69
struct Connection {
    query: Arc<Query>,
Roman Zeyde's avatar
Roman Zeyde committed
70
    last_header_entry: Option<HeaderEntry>,
71
    status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
72 73
    stream: TcpStream,
    addr: SocketAddr,
74
    chan: SyncChannel<Message>,
75
    stats: Arc<Stats>,
76 77
}

78
impl Connection {
79 80 81 82 83 84
    pub fn new(
        query: Arc<Query>,
        stream: TcpStream,
        addr: SocketAddr,
        stats: Arc<Stats>,
    ) -> Connection {
85
        Connection {
86
            query,
Roman Zeyde's avatar
Roman Zeyde committed
87
            last_header_entry: None, // disable header subscription for now
88
            status_hashes: HashMap::new(),
89 90
            stream,
            addr,
91
            chan: SyncChannel::new(10),
92
            stats,
93 94 95 96
        }
    }

    fn blockchain_headers_subscribe(&mut self) -> Result<Value> {
97
        let entry = self.query.get_best_header()?;
98
        let hex_header = hex::encode(serialize(entry.header()));
Roman Zeyde's avatar
Roman Zeyde committed
99 100 101
        let result = json!({"hex": hex_header, "height": entry.height()});
        self.last_header_entry = Some(entry);
        Ok(result)
102
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
103

104
    fn server_version(&self) -> Result<Value> {
105
        Ok(json!(["RustElectrum 0.1.0", "1.4"]))
106
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
107

108
    fn server_banner(&self) -> Result<Value> {
109
        Ok(json!(self.query.get_banner()?))
110
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
111

112
    fn server_donation_address(&self) -> Result<Value> {
113
        Ok(Value::Null)
114
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
115

116 117 118
    fn server_peers_subscribe(&self) -> Result<Value> {
        Ok(json!([]))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
119

120
    fn mempool_get_fee_histogram(&self) -> Result<Value> {
121
        Ok(json!(self.query.get_fee_histogram()))
122
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
123

124 125
    fn blockchain_block_header(&self, params: &[Value]) -> Result<Value> {
        let height = usize_from_value(params.get(0), "height")?;
126
        let cp_height = usize_from_value_or(params.get(1), "cp_height", 0)?;
127 128

        let raw_header_hex: String = self
129 130 131 132 133
            .query
            .get_headers(&[height])
            .into_iter()
            .map(|entry| hex::encode(&serialize(entry.header())))
            .collect();
134 135 136 137 138 139 140 141 142 143 144 145 146

        if cp_height == 0 {
            return Ok(json!(raw_header_hex));
        }
        let (branch, root) = self.query.get_header_merkle_proof(height, cp_height)?;

        let branch_vec: Vec<String> = branch.into_iter().map(|b| b.be_hex_string()).collect();

        return Ok(json!({
            "header": raw_header_hex,
            "root": root.be_hex_string(),
            "branch": branch_vec
        }));
147 148
    }

149 150 151
    fn blockchain_block_headers(&self, params: &[Value]) -> Result<Value> {
        let start_height = usize_from_value(params.get(0), "start_height")?;
        let count = usize_from_value(params.get(1), "count")?;
152
        let cp_height = usize_from_value_or(params.get(2), "cp_height", 0)?;
153
        let heights: Vec<usize> = (start_height..(start_height + count)).collect();
Roman Zeyde's avatar
Roman Zeyde committed
154 155
        let headers: Vec<String> = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
156 157
            .get_headers(&heights)
            .into_iter()
158
            .map(|entry| hex::encode(&serialize(entry.header())))
Roman Zeyde's avatar
Roman Zeyde committed
159
            .collect();
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

        if count == 0 || cp_height == 0 {
            return Ok(json!({
                "count": headers.len(),
                "hex": headers.join(""),
                "max": 2016,
            }));
        }

        let (branch, root) = self
            .query
            .get_header_merkle_proof(start_height + (count - 1), cp_height)?;

        let branch_vec: Vec<String> = branch.into_iter().map(|b| b.be_hex_string()).collect();

175 176 177 178
        Ok(json!({
            "count": headers.len(),
            "hex": headers.join(""),
            "max": 2016,
179 180
            "root": root.be_hex_string(),
            "branch" : branch_vec
181
        }))
182 183
    }

184
    fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
185 186
        let blocks_count = usize_from_value(params.get(0), "blocks_count")?;
        let fee_rate = self.query.estimate_fee(blocks_count); // in BTC/kB
187
        Ok(json!(fee_rate))
188
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
189

Roman Zeyde's avatar
Roman Zeyde committed
190
    fn blockchain_relayfee(&self) -> Result<Value> {
191
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
192 193
    }

194
    fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
195
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
196
        let status = self.query.status(&script_hash[..])?;
197
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
198 199
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
200
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
201

202
    fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
203
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
204
        let status = self.query.status(&script_hash[..])?;
205 206 207
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
208
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
209

Roman Zeyde's avatar
Roman Zeyde committed
210
    fn blockchain_scripthash_get_history(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
211
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
212
        let status = self.query.status(&script_hash[..])?;
Roman Zeyde's avatar
Roman Zeyde committed
213
        Ok(json!(Value::Array(
214 215
            status
                .history()
Roman Zeyde's avatar
Roman Zeyde committed
216 217 218 219
                .into_iter()
                .map(|item| json!({"height": item.0, "tx_hash": item.1.be_hex_string()}))
                .collect()
        )))
220
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
221

222 223
    fn blockchain_scripthash_listunspent(&self, params: &[Value]) -> Result<Value> {
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
224 225 226
        Ok(unspent_from_status(&self.query.status(&script_hash[..])?))
    }

227 228 229 230 231
    fn blockchain_transaction_broadcast(&self, params: &[Value]) -> Result<Value> {
        let tx = params.get(0).chain_err(|| "missing tx")?;
        let tx = tx.as_str().chain_err(|| "non-string tx")?;
        let tx = hex::decode(&tx).chain_err(|| "non-hex tx")?;
        let tx: Transaction = deserialize(&tx).chain_err(|| "failed to parse tx")?;
232
        let txid = self.query.broadcast(&tx)?;
233 234 235 236
        self.query.update_mempool()?;
        if let Err(e) = self.chan.sender().try_send(Message::PeriodicUpdate) {
            warn!("failed to issue PeriodicUpdate after broadcast: {}", e);
        }
237 238 239
        Ok(json!(txid.be_hex_string()))
    }

240
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
241
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
242 243 244 245 246
        let verbose = match params.get(1) {
            Some(value) => value.as_bool().chain_err(|| "non-bool verbose value")?,
            None => false,
        };
        Ok(self.query.get_transaction(&tx_hash, verbose)?)
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
247 248
    }

Roman Zeyde's avatar
Roman Zeyde committed
249 250
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
251
        let height = usize_from_value(params.get(1), "height")?;
Roman Zeyde's avatar
Roman Zeyde committed
252 253
        let (merkle, pos) = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
254 255 256 257 258 259 260 261 262 263
            .get_merkle_proof(&tx_hash, height)
            .chain_err(|| "cannot create merkle proof")?;
        let merkle: Vec<String> = merkle
            .into_iter()
            .map(|txid| txid.be_hex_string())
            .collect();
        Ok(json!({
                "block_height": height,
                "merkle": merkle,
                "pos": pos}))
264
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
265

266 267 268
    fn blockchain_transaction_id_from_pos(&self, params: &[Value]) -> Result<Value> {
        let height = usize_from_value(params.get(0), "height")?;
        let tx_pos = usize_from_value(params.get(1), "tx_pos")?;
269
        let want_merkle = bool_from_value_or(params.get(2), "merkle", false)?;
270 271 272 273 274 275 276 277 278 279 280 281 282

        let (txid, merkle) = self.query.get_id_from_pos(height, tx_pos, want_merkle)?;

        if !want_merkle {
            return Ok(json!(txid.be_hex_string()));
        }

        let merkle_vec: Vec<String> = merkle
            .into_iter()
            .map(|entry| entry.be_hex_string())
            .collect();

        Ok(json!({
283
            "tx_hash" : txid.be_hex_string(),
284 285 286
            "merkle" : merkle_vec}))
    }

287
    fn handle_command(&mut self, method: &str, params: &[Value], id: &Value) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
288 289
        let timer = self
            .stats
290 291 292
            .latency
            .with_label_values(&[method])
            .start_timer();
293
        let result = match method {
294
            "blockchain.block.header" => self.blockchain_block_header(&params),
295
            "blockchain.block.headers" => self.blockchain_block_headers(&params),
296
            "blockchain.estimatefee" => self.blockchain_estimatefee(&params),
297
            "blockchain.headers.subscribe" => self.blockchain_headers_subscribe(),
Roman Zeyde's avatar
Roman Zeyde committed
298
            "blockchain.relayfee" => self.blockchain_relayfee(),
299 300
            "blockchain.scripthash.get_balance" => self.blockchain_scripthash_get_balance(&params),
            "blockchain.scripthash.get_history" => self.blockchain_scripthash_get_history(&params),
301
            "blockchain.scripthash.listunspent" => self.blockchain_scripthash_listunspent(&params),
302
            "blockchain.scripthash.subscribe" => self.blockchain_scripthash_subscribe(&params),
303
            "blockchain.transaction.broadcast" => self.blockchain_transaction_broadcast(&params),
304 305
            "blockchain.transaction.get" => self.blockchain_transaction_get(&params),
            "blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(&params),
306 307 308
            "blockchain.transaction.id_from_pos" => {
                self.blockchain_transaction_id_from_pos(&params)
            }
309 310 311 312
            "mempool.get_fee_histogram" => self.mempool_get_fee_histogram(),
            "server.banner" => self.server_banner(),
            "server.donation_address" => self.server_donation_address(),
            "server.peers.subscribe" => self.server_peers_subscribe(),
313
            "server.ping" => Ok(Value::Null),
314
            "server.version" => self.server_version(),
315
            &_ => bail!("unknown method {} {:?}", method, params),
316
        };
317
        timer.observe_duration();
318
        // TODO: return application errors should be sent to the client
319 320 321
        Ok(match result {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(e) => {
Roman Zeyde's avatar
Roman Zeyde committed
322 323 324 325 326 327 328
                warn!(
                    "rpc #{} {} {:?} failed: {}",
                    id,
                    method,
                    params,
                    e.display_chain()
                );
329 330 331
                json!({"jsonrpc": "2.0", "id": id, "error": format!("{}", e)})
            }
        })
332 333
    }

Roman Zeyde's avatar
Roman Zeyde committed
334
    fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
Roman Zeyde's avatar
Roman Zeyde committed
335 336
        let timer = self
            .stats
337 338 339
            .latency
            .with_label_values(&["periodic_update"])
            .start_timer();
340
        let mut result = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
341
        if let Some(ref mut last_entry) = self.last_header_entry {
342
            let entry = self.query.get_best_header()?;
Roman Zeyde's avatar
Roman Zeyde committed
343 344
            if *last_entry != entry {
                *last_entry = entry;
345
                let hex_header = hex::encode(serialize(last_entry.header()));
Roman Zeyde's avatar
Roman Zeyde committed
346
                let header = json!({"hex": hex_header, "height": last_entry.height()});
Roman Zeyde's avatar
Roman Zeyde committed
347 348 349 350 351
                result.push(json!({
                    "jsonrpc": "2.0",
                    "method": "blockchain.headers.subscribe",
                    "params": [header]}));
            }
352 353
        }
        for (script_hash, status_hash) in self.status_hashes.iter_mut() {
354
            let status = self.query.status(&script_hash[..])?;
355
            let new_status_hash = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
356 357 358 359 360 361 362 363 364
            if new_status_hash == *status_hash {
                continue;
            }
            result.push(json!({
                "jsonrpc": "2.0",
                "method": "blockchain.scripthash.subscribe",
                "params": [script_hash.be_hex_string(), new_status_hash]}));
            *status_hash = new_status_hash;
        }
365 366 367 368
        timer.observe_duration();
        self.stats
            .subscriptions
            .set(self.status_hashes.len() as i64);
369 370 371
        Ok(result)
    }

372 373 374 375 376 377 378 379
    fn send_values(&mut self, values: &[Value]) -> Result<()> {
        for value in values {
            let line = value.to_string() + "\n";
            self.stream
                .write_all(line.as_bytes())
                .chain_err(|| format!("failed to send {}", value))?;
        }
        Ok(())
380 381
    }

382
    fn handle_replies(&mut self) -> Result<()> {
383
        let empty_params = json!([]);
Roman Zeyde's avatar
Roman Zeyde committed
384
        loop {
385
            let msg = self.chan.receiver().recv().chain_err(|| "channel closed")?;
386
            trace!("RPC {:?}", msg);
Roman Zeyde's avatar
Roman Zeyde committed
387 388 389
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
390 391 392 393 394
                    let reply = match (
                        cmd.get("method"),
                        cmd.get("params").unwrap_or_else(|| &empty_params),
                        cmd.get("id"),
                    ) {
Roman Zeyde's avatar
Roman Zeyde committed
395 396
                        (
                            Some(&Value::String(ref method)),
397
                            &Value::Array(ref params),
398
                            Some(ref id),
Roman Zeyde's avatar
Roman Zeyde committed
399 400 401
                        ) => self.handle_command(method, params, id)?,
                        _ => bail!("invalid command: {}", cmd),
                    };
402
                    self.send_values(&[reply])?
403
                }
404
                Message::PeriodicUpdate => {
Roman Zeyde's avatar
Roman Zeyde committed
405 406
                    let values = self
                        .update_subscriptions()
407 408
                        .chain_err(|| "failed to update subscriptions")?;
                    self.send_values(&values)?
Roman Zeyde's avatar
Roman Zeyde committed
409
                }
410
                Message::Done => return Ok(()),
411
            }
Roman Zeyde's avatar
Roman Zeyde committed
412 413 414
        }
    }

415
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
416
        loop {
417
            let mut line = Vec::<u8>::new();
Roman Zeyde's avatar
Roman Zeyde committed
418
            reader
419 420
                .read_until(b'\n', &mut line)
                .chain_err(|| "failed to read a request")?;
Roman Zeyde's avatar
Roman Zeyde committed
421
            if line.is_empty() {
422 423
                tx.send(Message::Done).chain_err(|| "channel closed")?;
                return Ok(());
Roman Zeyde's avatar
Roman Zeyde committed
424
            } else {
425 426 427 428 429
                if line.starts_with(&[22, 3, 1]) {
                    // (very) naive SSL handshake detection
                    let _ = tx.send(Message::Done);
                    bail!("invalid request - maybe SSL-encrypted data?: {:?}", line)
                }
430
                match String::from_utf8(line) {
Roman Zeyde's avatar
Roman Zeyde committed
431 432
                    Ok(req) => tx
                        .send(Message::Request(req))
433 434 435
                        .chain_err(|| "channel closed")?,
                    Err(err) => {
                        let _ = tx.send(Message::Done);
436
                        bail!("invalid UTF8: {}", err)
437 438
                    }
                }
Roman Zeyde's avatar
Roman Zeyde committed
439 440 441 442
            }
        }
    }

443
    pub fn run(mut self) {
444
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
445
        let tx = self.chan.sender();
446
        let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
447
        if let Err(e) = self.handle_replies() {
448 449 450 451 452 453
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
454
        debug!("[{}] shutting down connection", self.addr);
455
        let _ = self.stream.shutdown(Shutdown::Both);
456 457
        if let Err(err) = child.join().expect("receiver panicked") {
            error!("[{}] receiver failed: {}", self.addr, err);
458
        }
459 460 461
    }
}

462
#[derive(Debug)]
463 464
pub enum Message {
    Request(String),
465
    PeriodicUpdate,
466 467 468
    Done,
}

469 470 471 472 473
pub enum Notification {
    Periodic,
    Exit,
}

474
pub struct RPC {
475
    notification: Sender<Notification>,
Roman Zeyde's avatar
Roman Zeyde committed
476
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
477 478
}

479 480 481 482 483
struct Stats {
    latency: HistogramVec,
    subscriptions: Gauge,
}

484
impl RPC {
485 486
    fn start_notifier(
        notification: Channel<Notification>,
487
        senders: Arc<Mutex<Vec<SyncSender<Message>>>>,
488
        acceptor: Sender<Option<(TcpStream, SocketAddr)>>,
489
    ) {
490
        spawn_thread("notification", move || {
491
            for msg in notification.receiver().iter() {
492
                let mut senders = senders.lock().unwrap();
493
                match msg {
Roman Zeyde's avatar
Roman Zeyde committed
494 495 496 497 498 499 500 501
                    Notification::Periodic => {
                        for sender in senders.split_off(0) {
                            if let Err(TrySendError::Disconnected(_)) =
                                sender.try_send(Message::PeriodicUpdate)
                            {
                                continue;
                            }
                            senders.push(sender);
502
                        }
Roman Zeyde's avatar
Roman Zeyde committed
503
                    }
504
                    Notification::Exit => acceptor.send(None).unwrap(),
505 506
                }
            }
507
        });
508 509
    }

510
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
511
        let chan = Channel::new();
512
        let acceptor = chan.sender();
513
        spawn_thread("acceptor", move || {
514
            let listener = TcpListener::bind(addr).expect(&format!("bind({}) failed", addr));
515
            info!("RPC server running on {}", addr);
516 517
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
Roman Zeyde's avatar
Roman Zeyde committed
518 519 520
                stream
                    .set_nonblocking(false)
                    .expect("failed to set connection as blocking");
521
                acceptor.send(Some((stream, addr))).expect("send failed");
522 523 524 525 526
            }
        });
        chan
    }

527 528
    pub fn start(addr: SocketAddr, query: Arc<Query>, metrics: &Metrics) -> RPC {
        let stats = Arc::new(Stats {
529
            latency: metrics.histogram_vec(
530 531 532 533 534 535 536 537
                HistogramOpts::new("electrum_rpc", "Electrum RPC latency (seconds)"),
                &["method"],
            ),
            subscriptions: metrics.gauge(MetricOpts::new(
                "electrum_subscriptions",
                "# of Electrum subscriptions",
            )),
        });
538 539 540
        let notification = Channel::new();
        let handle = RPC {
            notification: notification.sender(),
Roman Zeyde's avatar
Roman Zeyde committed
541
            server: Some(spawn_thread("rpc", move || {
542 543 544
                let senders = Arc::new(Mutex::new(Vec::<SyncSender<Message>>::new()));
                let acceptor = RPC::start_acceptor(addr);
                RPC::start_notifier(notification, senders.clone(), acceptor.sender());
545
                let mut children = vec![];
546 547 548 549
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
                    let query = query.clone();
                    let senders = senders.clone();
                    let stats = stats.clone();
550
                    children.push(spawn_thread("peer", move || {
551 552 553 554 555
                        info!("[{}] connected peer", addr);
                        let conn = Connection::new(query, stream, addr, stats);
                        senders.lock().unwrap().push(conn.chan.sender());
                        conn.run();
                        info!("[{}] disconnected peer", addr);
556 557
                    }));
                }
558
                trace!("closing {} RPC connections", senders.lock().unwrap().len());
559 560 561
                for sender in senders.lock().unwrap().iter() {
                    let _ = sender.send(Message::Done);
                }
562
                trace!("waiting for {} RPC handling threads", children.len());
563 564
                for child in children {
                    let _ = child.join();
565
                }
Roman Zeyde's avatar
Roman Zeyde committed
566
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
567
            })),
568 569
        };
        handle
570 571 572
    }

    pub fn notify(&self) {
573 574
        self.notification.send(Notification::Periodic).unwrap();
    }
Roman Zeyde's avatar
Roman Zeyde committed
575
}
576

Roman Zeyde's avatar
Roman Zeyde committed
577 578
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
579
        trace!("stop accepting new RPCs");
580
        self.notification.send(Notification::Exit).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
581
        self.server.take().map(|t| t.join().unwrap());
Roman Zeyde's avatar
Roman Zeyde committed
582
        trace!("RPC server is stopped");
583
    }
Roman Zeyde's avatar
Roman Zeyde committed
584
}