rpc.rs 22.6 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 48
            }))
            .collect()
49 50 51
    ))
}

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

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

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

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

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

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

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

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

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

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

129 130 131 132 133 134 135 136 137 138 139
    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))
    }

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

Roman Zeyde's avatar
Roman Zeyde committed
157
    fn blockchain_block_get_header(&self, params: &[Value]) -> Result<Value> {
158
        let height = usize_from_value(params.get(0), "missing height")?;
159 160 161 162 163 164
        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
165 166
    }

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

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

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

185 186
    fn blockchain_address_subscribe(&mut self, params: &[Value]) -> Result<Value> {
        let addr = address_from_value(params.get(0)).chain_err(|| "bad address")?;
187
        let script_hash = compute_script_hash(&addr.script_pubkey().into_bytes());
188 189 190 191 192 193 194
        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)
    }

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

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

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

224 225 226 227 228 229 230 231 232 233 234 235 236
    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()
        )))
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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