rpc.rs 21.1 KB
Newer Older
1 2
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::network::serialize::{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 42 43 44 45 46 47 48 49 50 51 52 53
fn unspent_from_status(status: &Status) -> Value {
    json!(Value::Array(
        status
            .unspent()
            .into_iter()
            .map(|out| {
                json!({
                "height": out.height,
                "tx_pos": out.output_index,
                "tx_hash": out.txn_id.be_hex_string(),
                "value": out.value,
            })
            })
            .collect()
    ))
}

54 55 56 57 58 59 60 61
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))
}

62 63
fn jsonify_header(entry: &HeaderEntry) -> Value {
    let header = entry.header();
Roman Zeyde's avatar
Roman Zeyde committed
64
    json!({
65
        "block_height": entry.height(),
Roman Zeyde's avatar
Roman Zeyde committed
66 67 68 69 70 71 72 73 74
        "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
    })
}

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

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

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

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

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

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

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

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

131 132 133 134
    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
135 136
        let headers: Vec<String> = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
137 138
            .get_headers(&heights)
            .into_iter()
139
            .map(|entry| hex::encode(&serialize(entry.header()).unwrap()))
Roman Zeyde's avatar
Roman Zeyde committed
140
            .collect();
141 142 143 144 145
        Ok(json!({
            "count": headers.len(),
            "hex": headers.join(""),
            "max": 2016,
        }))
146 147
    }

Roman Zeyde's avatar
Roman Zeyde committed
148
    fn blockchain_block_get_header(&self, params: &[Value]) -> Result<Value> {
149
        let height = usize_from_value(params.get(0), "missing height")?;
150 151 152 153 154 155
        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
156 157
    }

158
    fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
159 160
        let blocks_count = usize_from_value(params.get(0), "blocks_count")?;
        let fee_rate = self.query.estimate_fee(blocks_count); // in BTC/kB
161
        Ok(json!(fee_rate))
162
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
163

Roman Zeyde's avatar
Roman Zeyde committed
164
    fn blockchain_relayfee(&self) -> Result<Value> {
165
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
166 167
    }

168
    fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
169
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
170
        let status = self.query.status(&script_hash[..])?;
171
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
172 173
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
174
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
175

176 177 178 179 180 181 182 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")?;
        let script_hash = compute_script_hash(&addr.script_pubkey().into_vec());
        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)
    }

186
    fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
187
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
188
        let status = self.query.status(&script_hash[..])?;
189 190 191
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
192
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
193

194 195 196 197 198 199 200 201 202
    fn blockchain_address_get_balance(&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_vec());
        let status = self.query.status(&script_hash[..])?;
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
    }

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

215 216
    fn blockchain_scripthash_listunspent(&self, params: &[Value]) -> Result<Value> {
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
217 218 219 220
        Ok(unspent_from_status(&self.query.status(&script_hash[..])?))
    }

    fn blockchain_address_listunspent(&self, params: &[Value]) -> Result<Value> {
221
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
222 223
        let script_hash = compute_script_hash(&addr.script_pubkey().into_vec());
        Ok(unspent_from_status(&self.query.status(&script_hash[..])?))
224 225
    }

226 227 228 229 230
    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")?;
231
        let txid = self.query.broadcast(&tx)?;
232 233 234 235
        self.query.update_mempool()?;
        if let Err(e) = self.chan.sender().try_send(Message::PeriodicUpdate) {
            warn!("failed to issue PeriodicUpdate after broadcast: {}", e);
        }
236 237 238
        Ok(json!(txid.be_hex_string()))
    }

239
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
240
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
241 242 243 244 245
        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
246 247
    }

Roman Zeyde's avatar
Roman Zeyde committed
248 249
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
250
        let height = usize_from_value(params.get(1), "height")?;
Roman Zeyde's avatar
Roman Zeyde committed
251 252
        let (merkle, pos) = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
253 254 255 256 257 258 259 260 261 262
            .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}))
263
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
264

265
    fn handle_command(&mut self, method: &str, params: &[Value], id: &Number) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
266 267
        let timer = self
            .stats
268 269 270
            .latency
            .with_label_values(&[method])
            .start_timer();
271 272 273 274 275 276 277
        let result = match method {
            "blockchain.headers.subscribe" => self.blockchain_headers_subscribe(),
            "server.version" => self.server_version(),
            "server.banner" => self.server_banner(),
            "server.donation_address" => self.server_donation_address(),
            "server.peers.subscribe" => self.server_peers_subscribe(),
            "mempool.get_fee_histogram" => self.mempool_get_fee_histogram(),
278
            "blockchain.block.headers" => self.blockchain_block_headers(&params),
Roman Zeyde's avatar
Roman Zeyde committed
279
            "blockchain.block.get_header" => self.blockchain_block_get_header(&params),
280
            "blockchain.estimatefee" => self.blockchain_estimatefee(&params),
Roman Zeyde's avatar
Roman Zeyde committed
281
            "blockchain.relayfee" => self.blockchain_relayfee(),
282
            "blockchain.address.subscribe" => self.blockchain_address_subscribe(&params),
283
            "blockchain.address.get_balance" => self.blockchain_address_get_balance(&params),
284
            "blockchain.address.listunspent" => self.blockchain_address_listunspent(&params),
285 286 287
            "blockchain.scripthash.subscribe" => self.blockchain_scripthash_subscribe(&params),
            "blockchain.scripthash.get_balance" => self.blockchain_scripthash_get_balance(&params),
            "blockchain.scripthash.get_history" => self.blockchain_scripthash_get_history(&params),
288
            "blockchain.scripthash.listunspent" => self.blockchain_scripthash_listunspent(&params),
289
            "blockchain.transaction.broadcast" => self.blockchain_transaction_broadcast(&params),
290 291 292
            "blockchain.transaction.get" => self.blockchain_transaction_get(&params),
            "blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(&params),
            &_ => bail!("unknown method {} {:?}", method, params),
293
        };
294
        timer.observe_duration();
295
        // TODO: return application errors should be sent to the client
296 297 298
        Ok(match result {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(e) => {
Roman Zeyde's avatar
Roman Zeyde committed
299 300 301 302 303 304 305
                warn!(
                    "rpc #{} {} {:?} failed: {}",
                    id,
                    method,
                    params,
                    e.display_chain()
                );
306 307 308
                json!({"jsonrpc": "2.0", "id": id, "error": format!("{}", e)})
            }
        })
309 310
    }

Roman Zeyde's avatar
Roman Zeyde committed
311
    fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
Roman Zeyde's avatar
Roman Zeyde committed
312 313
        let timer = self
            .stats
314 315 316
            .latency
            .with_label_values(&["periodic_update"])
            .start_timer();
317
        let mut result = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
318
        if let Some(ref mut last_entry) = self.last_header_entry {
319
            let entry = self.query.get_best_header()?;
Roman Zeyde's avatar
Roman Zeyde committed
320 321
            if *last_entry != entry {
                *last_entry = entry;
Roman Zeyde's avatar
Roman Zeyde committed
322 323
                let hex_header = hex::encode(serialize(last_entry.header()).unwrap());
                let header = json!({"hex": hex_header, "height": last_entry.height()});
Roman Zeyde's avatar
Roman Zeyde committed
324 325 326 327 328
                result.push(json!({
                    "jsonrpc": "2.0",
                    "method": "blockchain.headers.subscribe",
                    "params": [header]}));
            }
329 330
        }
        for (script_hash, status_hash) in self.status_hashes.iter_mut() {
331
            let status = self.query.status(&script_hash[..])?;
332
            let new_status_hash = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
333 334 335 336 337 338 339 340 341
            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;
        }
342 343 344 345
        timer.observe_duration();
        self.stats
            .subscriptions
            .set(self.status_hashes.len() as i64);
346 347 348
        Ok(result)
    }

349 350 351 352 353 354 355 356
    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(())
357 358
    }

359
    fn handle_replies(&mut self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
360
        loop {
361
            let msg = self.chan.receiver().recv().chain_err(|| "channel closed")?;
362
            trace!("RPC {:?}", msg);
Roman Zeyde's avatar
Roman Zeyde committed
363 364 365 366 367 368 369 370 371 372 373
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
                    let reply = match (cmd.get("method"), cmd.get("params"), cmd.get("id")) {
                        (
                            Some(&Value::String(ref method)),
                            Some(&Value::Array(ref params)),
                            Some(&Value::Number(ref id)),
                        ) => self.handle_command(method, params, id)?,
                        _ => bail!("invalid command: {}", cmd),
                    };
374
                    self.send_values(&[reply])?
375
                }
376
                Message::PeriodicUpdate => {
Roman Zeyde's avatar
Roman Zeyde committed
377 378
                    let values = self
                        .update_subscriptions()
379 380
                        .chain_err(|| "failed to update subscriptions")?;
                    self.send_values(&values)?
Roman Zeyde's avatar
Roman Zeyde committed
381
                }
382
                Message::Done => return Ok(()),
383
            }
Roman Zeyde's avatar
Roman Zeyde committed
384 385 386
        }
    }

387
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
388
        loop {
389
            let mut line = Vec::<u8>::new();
Roman Zeyde's avatar
Roman Zeyde committed
390
            reader
391 392
                .read_until(b'\n', &mut line)
                .chain_err(|| "failed to read a request")?;
Roman Zeyde's avatar
Roman Zeyde committed
393
            if line.is_empty() {
394 395
                tx.send(Message::Done).chain_err(|| "channel closed")?;
                return Ok(());
Roman Zeyde's avatar
Roman Zeyde committed
396
            } else {
397 398 399 400 401
                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)
                }
402
                match String::from_utf8(line) {
Roman Zeyde's avatar
Roman Zeyde committed
403 404
                    Ok(req) => tx
                        .send(Message::Request(req))
405 406 407
                        .chain_err(|| "channel closed")?,
                    Err(err) => {
                        let _ = tx.send(Message::Done);
408
                        bail!("invalid UTF8: {}", err)
409 410
                    }
                }
Roman Zeyde's avatar
Roman Zeyde committed
411 412 413 414
            }
        }
    }

415
    pub fn run(mut self) {
416
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
417
        let tx = self.chan.sender();
418
        let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
419
        if let Err(e) = self.handle_replies() {
420 421 422 423 424 425
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
426
        info!("[{}] shutting down connection", self.addr);
427
        let _ = self.stream.shutdown(Shutdown::Both);
428 429
        if let Err(err) = child.join().expect("receiver panicked") {
            error!("[{}] receiver failed: {}", self.addr, err);
430
        }
431 432 433
    }
}

434
#[derive(Debug)]
435 436
pub enum Message {
    Request(String),
437
    PeriodicUpdate,
438 439 440
    Done,
}

441 442 443 444 445
pub enum Notification {
    Periodic,
    Exit,
}

446
pub struct RPC {
447
    notification: Sender<Notification>,
Roman Zeyde's avatar
Roman Zeyde committed
448
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
449 450
}

451 452 453 454 455
struct Stats {
    latency: HistogramVec,
    subscriptions: Gauge,
}

456
impl RPC {
457 458
    fn start_notifier(
        notification: Channel<Notification>,
459
        senders: Arc<Mutex<Vec<SyncSender<Message>>>>,
460
        acceptor: Sender<Option<(TcpStream, SocketAddr)>>,
461
    ) {
462
        spawn_thread("notification", move || {
463
            for msg in notification.receiver().iter() {
464
                let mut senders = senders.lock().unwrap();
465 466 467 468 469 470 471 472 473 474
                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(),
475 476
                }
            }
477
        });
478 479
    }

480
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
481
        let chan = Channel::new();
482
        let acceptor = chan.sender();
483
        spawn_thread("acceptor", move || {
484
            let listener = TcpListener::bind(addr).expect(&format!("bind({}) failed", addr));
485
            info!("RPC server running on {}", addr);
486 487
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
488
                acceptor.send(Some((stream, addr))).expect("send failed");
489 490 491 492 493
            }
        });
        chan
    }

494 495
    pub fn start(addr: SocketAddr, query: Arc<Query>, metrics: &Metrics) -> RPC {
        let stats = Arc::new(Stats {
496
            latency: metrics.histogram_vec(
497 498 499 500 501 502 503 504
                HistogramOpts::new("electrum_rpc", "Electrum RPC latency (seconds)"),
                &["method"],
            ),
            subscriptions: metrics.gauge(MetricOpts::new(
                "electrum_subscriptions",
                "# of Electrum subscriptions",
            )),
        });
505 506 507
        let notification = Channel::new();
        let handle = RPC {
            notification: notification.sender(),
Roman Zeyde's avatar
Roman Zeyde committed
508
            server: Some(spawn_thread("rpc", move || {
509 510 511
                let senders = Arc::new(Mutex::new(Vec::<SyncSender<Message>>::new()));
                let acceptor = RPC::start_acceptor(addr);
                RPC::start_notifier(notification, senders.clone(), acceptor.sender());
512
                let mut children = vec![];
513 514 515 516
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
                    let query = query.clone();
                    let senders = senders.clone();
                    let stats = stats.clone();
517
                    children.push(spawn_thread("peer", move || {
518 519 520 521 522
                        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);
523 524
                    }));
                }
Roman Zeyde's avatar
Roman Zeyde committed
525
                trace!("closing RPC connections");
526 527 528 529 530
                for sender in senders.lock().unwrap().iter() {
                    let _ = sender.send(Message::Done);
                }
                for child in children {
                    let _ = child.join();
531
                }
Roman Zeyde's avatar
Roman Zeyde committed
532
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
533
            })),
534 535
        };
        handle
536 537 538
    }

    pub fn notify(&self) {
539 540
        self.notification.send(Notification::Periodic).unwrap();
    }
Roman Zeyde's avatar
Roman Zeyde committed
541
}
542

Roman Zeyde's avatar
Roman Zeyde committed
543 544
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
545
        trace!("stop accepting new RPCs");
546
        self.notification.send(Notification::Exit).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
547
        self.server.take().map(|t| t.join().unwrap());
Roman Zeyde's avatar
Roman Zeyde committed
548
        trace!("RPC server is stopped");
549
    }
Roman Zeyde's avatar
Roman Zeyde committed
550
}