rpc.rs 21.6 KB
Newer Older
1
use bitcoin::blockdata::transaction::Transaction;
2
use bitcoin::consensus::encode::{deserialize, serialize};
Roman Zeyde's avatar
Roman Zeyde committed
3 4
use bitcoin_hashes::hex::{FromHex, ToHex};
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
5
use error_chain::ChainedError;
6
use hex;
7
use serde_json::{from_str, 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::sync::mpsc::{Sender, SyncSender, TrySendError};
12
use std::sync::{Arc, Mutex};
13
use std::thread;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
14

Roman Zeyde's avatar
Roman Zeyde committed
15 16 17 18
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
19

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

28 29 30 31 32 33
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)
}

34 35 36 37 38 39 40
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)
}

41 42 43
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))?;
44 45 46 47 48 49 50 51
    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)
52 53
}

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

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

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

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

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

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

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

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

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

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

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

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

Roman Zeyde's avatar
Roman Zeyde committed
141
        let branch_vec: Vec<String> = branch.into_iter().map(|b| b.to_hex()).collect();
142 143 144

        return Ok(json!({
            "header": raw_header_hex,
Roman Zeyde's avatar
Roman Zeyde committed
145
            "root": root.to_hex(),
146 147
            "branch": branch_vec
        }));
148 149
    }

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

        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)?;

Roman Zeyde's avatar
Roman Zeyde committed
174
        let branch_vec: Vec<String> = branch.into_iter().map(|b| b.to_hex()).collect();
175

176 177 178 179
        Ok(json!({
            "count": headers.len(),
            "hex": headers.join(""),
            "max": 2016,
Roman Zeyde's avatar
Roman Zeyde committed
180
            "root": root.to_hex(),
181
            "branch" : branch_vec
182
        }))
183 184
    }

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

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

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

203
    fn blockchain_scripthash_get_balance(&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[..])?;
206 207 208
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
209
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
210

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
                .into_iter()
Roman Zeyde's avatar
Roman Zeyde committed
218
                .map(|item| json!({"height": item.0, "tx_hash": item.1.to_hex()}))
Roman Zeyde's avatar
Roman Zeyde committed
219 220
                .collect()
        )))
221
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
222

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

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

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

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

264 265 266
    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")?;
267
        let want_merkle = bool_from_value_or(params.get(2), "merkle", false)?;
268 269 270 271

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

        if !want_merkle {
Roman Zeyde's avatar
Roman Zeyde committed
272
            return Ok(json!(txid.to_hex()));
273 274
        }

Roman Zeyde's avatar
Roman Zeyde committed
275
        let merkle_vec: Vec<String> = merkle.into_iter().map(|entry| entry.to_hex()).collect();
276 277

        Ok(json!({
Roman Zeyde's avatar
Roman Zeyde committed
278
            "tx_hash" : txid.to_hex(),
279 280 281
            "merkle" : merkle_vec}))
    }

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

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

367 368 369 370 371 372 373 374
    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(())
375 376
    }

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

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

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

457
#[derive(Debug)]
458 459
pub enum Message {
    Request(String),
460
    PeriodicUpdate,
461 462 463
    Done,
}

464 465 466 467 468
pub enum Notification {
    Periodic,
    Exit,
}

469
pub struct RPC {
470
    notification: Sender<Notification>,
Roman Zeyde's avatar
Roman Zeyde committed
471
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
472 473
}

474 475 476 477 478
struct Stats {
    latency: HistogramVec,
    subscriptions: Gauge,
}

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

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

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