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

16
use index::compute_script_hash;
17
use metrics::{Gauge, HistogramOpts, HistogramVec, MetricOpts, Metrics};
18
use query::{Query, Status};
19
use util::{spawn_thread, Channel, HeaderEntry, SyncChannel};
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
20

Roman Zeyde's avatar
Roman Zeyde committed
21
use errors::*;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
22

Roman Zeyde's avatar
Roman Zeyde committed
23
// TODO: Sha256dHash should be a generic hash-container (since script hash is single SHA256)
Roman Zeyde's avatar
Roman Zeyde committed
24 25
fn hash_from_value(val: Option<&Value>) -> Result<Sha256dHash> {
    let script_hash = val.chain_err(|| "missing hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
26 27 28 29 30
    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)
}

31 32 33 34 35 36
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)
}

37 38 39 40 41
fn unspent_from_status(status: &Status) -> Value {
    json!(Value::Array(
        status
            .unspent()
            .into_iter()
Roman Zeyde's avatar
Roman Zeyde committed
42
            .map(|out| json!({
43 44 45 46
                "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
47
            })).collect()
48 49 50
    ))
}

51 52 53 54 55 56 57 58
fn address_from_value(val: Option<&Value>) -> Result<Address> {
    let addr = val
        .chain_err(|| "no address")?
        .as_str()
        .chain_err(|| "non-string address")?;
    Address::from_str(addr).chain_err(|| format!("invalid address {}", addr))
}

59 60
fn jsonify_header(entry: &HeaderEntry) -> Value {
    let header = entry.header();
Roman Zeyde's avatar
Roman Zeyde committed
61
    json!({
62
        "block_height": entry.height(),
Roman Zeyde's avatar
Roman Zeyde committed
63 64 65 66 67 68 69 70 71
        "version": header.version,
        "prev_block_hash": header.prev_blockhash.be_hex_string(),
        "merkle_root": header.merkle_root.be_hex_string(),
        "timestamp": header.time,
        "bits": header.bits,
        "nonce": header.nonce
    })
}

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

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

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

108
    fn server_version(&self) -> Result<Value> {
109
        Ok(json!(["RustElectrum 0.1.0", "1.2"]))
110
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
111

112
    fn server_banner(&self) -> Result<Value> {
113
        Ok(json!("Welcome to RustElectrum Server!\n"))
114
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
115

116
    fn server_donation_address(&self) -> Result<Value> {
117
        Ok(Value::Null)
118
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
119

120 121 122
    fn server_peers_subscribe(&self) -> Result<Value> {
        Ok(json!([]))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
123

124
    fn mempool_get_fee_histogram(&self) -> Result<Value> {
125
        Ok(json!(self.query.get_fee_histogram()))
126
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
127

128 129 130 131 132 133 134 135 136 137 138
    fn blockchain_block_header(&self, params: &[Value]) -> Result<Value> {
        let height = usize_from_value(params.get(0), "height")?;
        let header: String = self
            .query
            .get_headers(&[height])
            .into_iter()
            .map(|entry| hex::encode(&serialize(entry.header())))
            .collect();
        Ok(json!(header))
    }

139 140 141 142
    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")?;
        let heights: Vec<usize> = (start_height..(start_height + count)).collect();
Roman Zeyde's avatar
Roman Zeyde committed
143 144
        let headers: Vec<String> = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
145 146
            .get_headers(&heights)
            .into_iter()
147
            .map(|entry| hex::encode(&serialize(entry.header())))
Roman Zeyde's avatar
Roman Zeyde committed
148
            .collect();
149 150 151 152 153
        Ok(json!({
            "count": headers.len(),
            "hex": headers.join(""),
            "max": 2016,
        }))
154 155
    }

Roman Zeyde's avatar
Roman Zeyde committed
156
    fn blockchain_block_get_header(&self, params: &[Value]) -> Result<Value> {
157
        let height = usize_from_value(params.get(0), "missing height")?;
158 159 160 161 162 163
        let mut entries = self.query.get_headers(&[height]);
        let entry = entries
            .pop()
            .chain_err(|| format!("missing header #{}", height))?;
        assert_eq!(entries.len(), 0);
        Ok(json!(jsonify_header(&entry)))
Roman Zeyde's avatar
Roman Zeyde committed
164 165
    }

166
    fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
167 168
        let blocks_count = usize_from_value(params.get(0), "blocks_count")?;
        let fee_rate = self.query.estimate_fee(blocks_count); // in BTC/kB
169
        Ok(json!(fee_rate))
170
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
171

Roman Zeyde's avatar
Roman Zeyde committed
172
    fn blockchain_relayfee(&self) -> Result<Value> {
173
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
174 175
    }

176
    fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
177
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
178
        let status = self.query.status(&script_hash[..])?;
179
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
180 181
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
182
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
183

184 185
    fn blockchain_address_subscribe(&mut self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
186
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
187 188 189 190 191 192 193
        let status = self.query.status(&script_hash[..])?;
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
        let script_hash: Sha256dHash = deserialize(&script_hash).unwrap();
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
    }

194
    fn blockchain_scripthash_get_balance(&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 198 199
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
200
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
201

202 203
    fn blockchain_address_get_balance(&self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
204
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
205 206 207 208 209 210
        let status = self.query.status(&script_hash[..])?;
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
    }

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

223 224 225 226 227 228 229 230 231 232 233 234 235
    fn blockchain_address_get_history(&self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
        let status = self.query.status(&script_hash[..])?;
        Ok(json!(Value::Array(
            status
                .history()
                .into_iter()
                .map(|item| json!({"height": item.0, "tx_hash": item.1.be_hex_string()}))
                .collect()
        )))
    }

236 237
    fn blockchain_scripthash_listunspent(&self, params: &[Value]) -> Result<Value> {
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
238 239 240 241
        Ok(unspent_from_status(&self.query.status(&script_hash[..])?))
    }

    fn blockchain_address_listunspent(&self, params: &[Value]) -> Result<Value> {
242
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
243
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
244
        Ok(unspent_from_status(&self.query.status(&script_hash[..])?))
245 246
    }

247 248 249 250 251
    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")?;
252
        let txid = self.query.broadcast(&tx)?;
253 254 255 256
        self.query.update_mempool()?;
        if let Err(e) = self.chan.sender().try_send(Message::PeriodicUpdate) {
            warn!("failed to issue PeriodicUpdate after broadcast: {}", e);
        }
257 258 259
        Ok(json!(txid.be_hex_string()))
    }

260
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
261
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
262 263 264 265 266
        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
267 268
    }

Roman Zeyde's avatar
Roman Zeyde committed
269 270
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
271
        let height = usize_from_value(params.get(1), "height")?;
Roman Zeyde's avatar
Roman Zeyde committed
272 273
        let (merkle, pos) = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
274 275 276 277 278 279 280 281 282 283
            .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}))
284
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
285

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

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

373 374 375 376 377 378 379 380
    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(())
381 382
    }

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

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

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

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

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

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

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

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

509
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
510
        let chan = Channel::new();
511
        let acceptor = chan.sender();
512
        spawn_thread("acceptor", move || {
513
            let listener = TcpListener::bind(addr).expect(&format!("bind({}) failed", addr));
514
            info!("RPC server running on {}", addr);
515 516
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
517
                acceptor.send(Some((stream, addr))).expect("send failed");
518 519 520 521 522
            }
        });
        chan
    }

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

    pub fn notify(&self) {
568 569
        self.notification.send(Notification::Periodic).unwrap();
    }
Roman Zeyde's avatar
Roman Zeyde committed
570
}
571

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