rpc.rs 11.9 KB
Newer Older
kenshin-samourai's avatar
kenshin-samourai committed
1
use bitcoin::consensus::encode::serialize;
Roman Zeyde's avatar
Roman Zeyde committed
2 3
use bitcoin_hashes::hex::{FromHex, ToHex};
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
4
use error_chain::ChainedError;
5
use hex;
6
use serde_json::{from_str, Value};
Roman Zeyde's avatar
Roman Zeyde committed
7
use std::collections::HashMap;
8
use std::io::{BufRead, BufReader, Write};
9
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
10
use std::sync::mpsc::{Sender, SyncSender, TrySendError};
11
use std::sync::{Arc, Mutex};
12
use std::thread;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
13

Roman Zeyde's avatar
Roman Zeyde committed
14
use crate::errors::*;
kenshin-samourai's avatar
kenshin-samourai committed
15
use crate::query::Query;
Roman Zeyde's avatar
Roman Zeyde committed
16
use crate::util::{spawn_thread, Channel, HeaderEntry, SyncChannel};
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
17

18 19
const ELECTRS_VERSION: &str = env!("CARGO_PKG_VERSION");
const PROTOCOL_VERSION: &str = "1.4";
20

21

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

30 31
struct Connection {
    query: Arc<Query>,
Roman Zeyde's avatar
Roman Zeyde committed
32
    last_header_entry: Option<HeaderEntry>,
33
    status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
34 35
    stream: TcpStream,
    addr: SocketAddr,
36
    chan: SyncChannel<Message>,
37 38
}

39
impl Connection {
40 41 42 43 44
    pub fn new(
        query: Arc<Query>,
        stream: TcpStream,
        addr: SocketAddr,
    ) -> Connection {
45
        Connection {
46
            query,
Roman Zeyde's avatar
Roman Zeyde committed
47
            last_header_entry: None, // disable header subscription for now
48
            status_hashes: HashMap::new(),
49 50
            stream,
            addr,
51
            chan: SyncChannel::new(10),
52 53 54
        }
    }

55
    fn server_version(&self) -> Result<Value> {
56 57 58 59
        Ok(json!([
            format!("electrs {}", ELECTRS_VERSION),
            PROTOCOL_VERSION
        ]))
60
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
61

Roman Zeyde's avatar
Roman Zeyde committed
62
    fn blockchain_scripthash_get_history(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
63
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
64
        let status = self.query.status(&script_hash[..])?;
Roman Zeyde's avatar
Roman Zeyde committed
65
        Ok(json!(Value::Array(
66 67
            status
                .history()
Roman Zeyde's avatar
Roman Zeyde committed
68
                .into_iter()
Roman Zeyde's avatar
Roman Zeyde committed
69
                .map(|item| json!({"height": item.0, "tx_hash": item.1.to_hex()}))
Roman Zeyde's avatar
Roman Zeyde committed
70 71
                .collect()
        )))
72
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
73

74
    fn handle_command(&mut self, method: &str, params: &[Value], id: &Value) -> Result<Value> {
75 76
        let result = match method {
            "blockchain.scripthash.get_history" => self.blockchain_scripthash_get_history(&params),
77
            "server.ping" => Ok(Value::Null),
78
            "server.version" => self.server_version(),
79
            &_ => bail!("unknown method {} {:?}", method, params),
80
        };
81
        // TODO: return application errors should be sent to the client
82 83 84
        Ok(match result {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(e) => {
Roman Zeyde's avatar
Roman Zeyde committed
85 86 87 88 89 90 91
                warn!(
                    "rpc #{} {} {:?} failed: {}",
                    id,
                    method,
                    params,
                    e.display_chain()
                );
92 93 94
                json!({"jsonrpc": "2.0", "id": id, "error": format!("{}", e)})
            }
        })
95 96
    }

Roman Zeyde's avatar
Roman Zeyde committed
97
    fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
98
        let mut result = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
99
        if let Some(ref mut last_entry) = self.last_header_entry {
100
            let entry = self.query.get_best_header()?;
Roman Zeyde's avatar
Roman Zeyde committed
101 102
            if *last_entry != entry {
                *last_entry = entry;
103
                let hex_header = hex::encode(serialize(last_entry.header()));
Roman Zeyde's avatar
Roman Zeyde committed
104
                let header = json!({"hex": hex_header, "height": last_entry.height()});
Roman Zeyde's avatar
Roman Zeyde committed
105 106 107 108 109
                result.push(json!({
                    "jsonrpc": "2.0",
                    "method": "blockchain.headers.subscribe",
                    "params": [header]}));
            }
110 111
        }
        for (script_hash, status_hash) in self.status_hashes.iter_mut() {
112
            let status = self.query.status(&script_hash[..])?;
113
            let new_status_hash = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
114 115 116 117 118 119
            if new_status_hash == *status_hash {
                continue;
            }
            result.push(json!({
                "jsonrpc": "2.0",
                "method": "blockchain.scripthash.subscribe",
Roman Zeyde's avatar
Roman Zeyde committed
120
                "params": [script_hash.to_hex(), new_status_hash]}));
121 122 123 124 125
            *status_hash = new_status_hash;
        }
        Ok(result)
    }

126 127 128 129 130 131 132 133
    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(())
134 135
    }

136
    fn handle_replies(&mut self) -> Result<()> {
137
        let empty_params = json!([]);
Roman Zeyde's avatar
Roman Zeyde committed
138
        loop {
139
            let msg = self.chan.receiver().recv().chain_err(|| "channel closed")?;
140
            trace!("RPC {:?}", msg);
Roman Zeyde's avatar
Roman Zeyde committed
141 142 143
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
144 145 146 147 148
                    let reply = match (
                        cmd.get("method"),
                        cmd.get("params").unwrap_or_else(|| &empty_params),
                        cmd.get("id"),
                    ) {
Roman Zeyde's avatar
Roman Zeyde committed
149 150
                        (
                            Some(&Value::String(ref method)),
151
                            &Value::Array(ref params),
152
                            Some(ref id),
Roman Zeyde's avatar
Roman Zeyde committed
153 154 155
                        ) => self.handle_command(method, params, id)?,
                        _ => bail!("invalid command: {}", cmd),
                    };
156
                    self.send_values(&[reply])?
157
                }
158
                Message::PeriodicUpdate => {
Roman Zeyde's avatar
Roman Zeyde committed
159 160
                    let values = self
                        .update_subscriptions()
161 162
                        .chain_err(|| "failed to update subscriptions")?;
                    self.send_values(&values)?
Roman Zeyde's avatar
Roman Zeyde committed
163
                }
164
                Message::Done => return Ok(()),
165
            }
Roman Zeyde's avatar
Roman Zeyde committed
166 167 168
        }
    }

169
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
170
        loop {
171
            let mut line = Vec::<u8>::new();
Roman Zeyde's avatar
Roman Zeyde committed
172
            reader
173 174
                .read_until(b'\n', &mut line)
                .chain_err(|| "failed to read a request")?;
Roman Zeyde's avatar
Roman Zeyde committed
175
            if line.is_empty() {
176 177
                tx.send(Message::Done).chain_err(|| "channel closed")?;
                return Ok(());
Roman Zeyde's avatar
Roman Zeyde committed
178
            } else {
179 180 181 182 183
                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)
                }
184
                match String::from_utf8(line) {
Roman Zeyde's avatar
Roman Zeyde committed
185 186
                    Ok(req) => tx
                        .send(Message::Request(req))
187 188 189
                        .chain_err(|| "channel closed")?,
                    Err(err) => {
                        let _ = tx.send(Message::Done);
190
                        bail!("invalid UTF8: {}", err)
191 192
                    }
                }
Roman Zeyde's avatar
Roman Zeyde committed
193 194 195 196
            }
        }
    }

197
    pub fn run(mut self) {
198
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
199
        let tx = self.chan.sender();
200
        let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
201
        if let Err(e) = self.handle_replies() {
202 203 204 205 206 207
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
208
        debug!("[{}] shutting down connection", self.addr);
209
        let _ = self.stream.shutdown(Shutdown::Both);
210 211
        if let Err(err) = child.join().expect("receiver panicked") {
            error!("[{}] receiver failed: {}", self.addr, err);
212
        }
213 214 215
    }
}

216
#[derive(Debug)]
217 218
pub enum Message {
    Request(String),
219
    PeriodicUpdate,
220 221 222
    Done,
}

223 224 225 226 227
pub enum Notification {
    Periodic,
    Exit,
}

228
pub struct RPC {
229
    notification: Sender<Notification>,
Roman Zeyde's avatar
Roman Zeyde committed
230
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
231 232 233
}

impl RPC {
234 235
    fn start_notifier(
        notification: Channel<Notification>,
236
        senders: Arc<Mutex<Vec<SyncSender<Message>>>>,
237
        acceptor: Sender<Option<(TcpStream, SocketAddr)>>,
238
    ) {
239
        spawn_thread("notification", move || {
240
            for msg in notification.receiver().iter() {
241
                let mut senders = senders.lock().unwrap();
242
                match msg {
Roman Zeyde's avatar
Roman Zeyde committed
243 244 245 246 247 248 249 250
                    Notification::Periodic => {
                        for sender in senders.split_off(0) {
                            if let Err(TrySendError::Disconnected(_)) =
                                sender.try_send(Message::PeriodicUpdate)
                            {
                                continue;
                            }
                            senders.push(sender);
251
                        }
Roman Zeyde's avatar
Roman Zeyde committed
252
                    }
253
                    Notification::Exit => acceptor.send(None).unwrap(),
254 255
                }
            }
256
        });
257 258
    }

259
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
Roman Zeyde's avatar
Roman Zeyde committed
260
        let chan = Channel::unbounded();
261
        let acceptor = chan.sender();
262
        spawn_thread("acceptor", move || {
Roman Zeyde's avatar
Roman Zeyde committed
263 264
            let listener =
                TcpListener::bind(addr).unwrap_or_else(|e| panic!("bind({}) failed: {}", addr, e));
265 266 267 268
            info!(
                "Electrum RPC server running on {} (protocol {})",
                addr, PROTOCOL_VERSION
            );
269 270
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
Roman Zeyde's avatar
Roman Zeyde committed
271 272 273
                stream
                    .set_nonblocking(false)
                    .expect("failed to set connection as blocking");
274
                acceptor.send(Some((stream, addr))).expect("send failed");
275 276 277 278 279
            }
        });
        chan
    }

280
    pub fn start(addr: SocketAddr, query: Arc<Query>) -> RPC {
Roman Zeyde's avatar
Roman Zeyde committed
281
        let notification = Channel::unbounded();
282

Roman Zeyde's avatar
Roman Zeyde committed
283
        RPC {
284
            notification: notification.sender(),
Roman Zeyde's avatar
Roman Zeyde committed
285
            server: Some(spawn_thread("rpc", move || {
286 287 288
                let senders = Arc::new(Mutex::new(Vec::<SyncSender<Message>>::new()));
                let acceptor = RPC::start_acceptor(addr);
                RPC::start_notifier(notification, senders.clone(), acceptor.sender());
289
                let mut children = vec![];
290 291 292
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
                    let query = query.clone();
                    let senders = senders.clone();
293
                    children.push(spawn_thread("peer", move || {
294
                        info!("[{}] connected peer", addr);
295
                        let conn = Connection::new(query, stream, addr);
296 297 298
                        senders.lock().unwrap().push(conn.chan.sender());
                        conn.run();
                        info!("[{}] disconnected peer", addr);
299 300
                    }));
                }
301
                trace!("closing {} RPC connections", senders.lock().unwrap().len());
302 303 304
                for sender in senders.lock().unwrap().iter() {
                    let _ = sender.send(Message::Done);
                }
305
                trace!("waiting for {} RPC handling threads", children.len());
306 307
                for child in children {
                    let _ = child.join();
308
                }
Roman Zeyde's avatar
Roman Zeyde committed
309
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
310
            })),
Roman Zeyde's avatar
Roman Zeyde committed
311
        }
312 313 314
    }

    pub fn notify(&self) {
315 316
        self.notification.send(Notification::Periodic).unwrap();
    }
Roman Zeyde's avatar
Roman Zeyde committed
317
}
318

Roman Zeyde's avatar
Roman Zeyde committed
319 320
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
321
        trace!("stop accepting new RPCs");
322
        self.notification.send(Notification::Exit).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
323 324 325
        if let Some(handle) = self.server.take() {
            handle.join().unwrap();
        }
Roman Zeyde's avatar
Roman Zeyde committed
326
        trace!("RPC server is stopped");
327
    }
Roman Zeyde's avatar
Roman Zeyde committed
328
}