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

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

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

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

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

173 174
    fn blockchain_address_subscribe(&mut self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
175
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
176 177 178 179 180 181 182
        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)
    }

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

191 192
    fn blockchain_address_get_balance(&self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
193
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
194 195 196 197 198 199
        let status = self.query.status(&script_hash[..])?;
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
    }

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

212 213 214 215 216 217 218 219 220 221 222 223 224
    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()
        )))
    }

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

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

236 237 238 239 240
    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")?;
241
        let txid = self.query.broadcast(&tx)?;
242 243 244 245
        self.query.update_mempool()?;
        if let Err(e) = self.chan.sender().try_send(Message::PeriodicUpdate) {
            warn!("failed to issue PeriodicUpdate after broadcast: {}", e);
        }
246 247 248
        Ok(json!(txid.be_hex_string()))
    }

249
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
250
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
251 252 253 254 255
        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
256 257
    }

Roman Zeyde's avatar
Roman Zeyde committed
258 259
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
260
        let height = usize_from_value(params.get(1), "height")?;
Roman Zeyde's avatar
Roman Zeyde committed
261 262
        let (merkle, pos) = self
            .query
Roman Zeyde's avatar
Roman Zeyde committed
263 264 265 266 267 268 269 270 271 272
            .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}))
273
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
274

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

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

360 361 362 363 364 365 366 367
    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(())
368 369
    }

370
    fn handle_replies(&mut self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
371
        loop {
372
            let msg = self.chan.receiver().recv().chain_err(|| "channel closed")?;
373
            trace!("RPC {:?}", msg);
Roman Zeyde's avatar
Roman Zeyde committed
374 375 376 377 378 379 380 381 382 383 384
            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),
                    };
385
                    self.send_values(&[reply])?
386
                }
387
                Message::PeriodicUpdate => {
Roman Zeyde's avatar
Roman Zeyde committed
388 389
                    let values = self
                        .update_subscriptions()
390 391
                        .chain_err(|| "failed to update subscriptions")?;
                    self.send_values(&values)?
Roman Zeyde's avatar
Roman Zeyde committed
392
                }
393
                Message::Done => return Ok(()),
394
            }
Roman Zeyde's avatar
Roman Zeyde committed
395 396 397
        }
    }

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

426
    pub fn run(mut self) {
427
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
428
        let tx = self.chan.sender();
429
        let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
430
        if let Err(e) = self.handle_replies() {
431 432 433 434 435 436
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
437
        debug!("[{}] shutting down connection", self.addr);
438
        let _ = self.stream.shutdown(Shutdown::Both);
439 440
        if let Err(err) = child.join().expect("receiver panicked") {
            error!("[{}] receiver failed: {}", self.addr, err);
441
        }
442 443 444
    }
}

445
#[derive(Debug)]
446 447
pub enum Message {
    Request(String),
448
    PeriodicUpdate,
449 450 451
    Done,
}

452 453 454 455 456
pub enum Notification {
    Periodic,
    Exit,
}

457
pub struct RPC {
458
    notification: Sender<Notification>,
Roman Zeyde's avatar
Roman Zeyde committed
459
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
460 461
}

462 463 464 465 466
struct Stats {
    latency: HistogramVec,
    subscriptions: Gauge,
}

467
impl RPC {
468 469
    fn start_notifier(
        notification: Channel<Notification>,
470
        senders: Arc<Mutex<Vec<SyncSender<Message>>>>,
471
        acceptor: Sender<Option<(TcpStream, SocketAddr)>>,
472
    ) {
473
        spawn_thread("notification", move || {
474
            for msg in notification.receiver().iter() {
475
                let mut senders = senders.lock().unwrap();
476 477 478 479 480 481 482 483 484 485
                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(),
486 487
                }
            }
488
        });
489 490
    }

491
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
492
        let chan = Channel::new();
493
        let acceptor = chan.sender();
494
        spawn_thread("acceptor", move || {
495
            let listener = TcpListener::bind(addr).expect(&format!("bind({}) failed", addr));
496
            info!("RPC server running on {}", addr);
497 498
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
499
                acceptor.send(Some((stream, addr))).expect("send failed");
500 501 502 503 504
            }
        });
        chan
    }

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

    pub fn notify(&self) {
550 551
        self.notification.send(Notification::Periodic).unwrap();
    }
Roman Zeyde's avatar
Roman Zeyde committed
552
}
553

Roman Zeyde's avatar
Roman Zeyde committed
554 555
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
556
        trace!("stop accepting new RPCs");
557
        self.notification.send(Notification::Exit).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
558
        self.server.take().map(|t| t.join().unwrap());
Roman Zeyde's avatar
Roman Zeyde committed
559
        trace!("RPC server is stopped");
560
    }
Roman Zeyde's avatar
Roman Zeyde committed
561
}