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

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

kenshin-samourai's avatar
kenshin-samourai committed
16
// Indexer version
17
const ADDRINDEXRS_VERSION: &str = env!("CARGO_PKG_VERSION");
kenshin-samourai's avatar
kenshin-samourai committed
18
// Version of the simulated electrum protocol
19
const PROTOCOL_VERSION: &str = "1.4";
20

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

kenshin-samourai's avatar
kenshin-samourai committed
32 33 34
//
// Connection with a RPC client
//
35 36
struct Connection {
    query: Arc<Query>,
37 38
    stream: TcpStream,
    addr: SocketAddr,
39
    chan: SyncChannel<Message>,
40 41
}

42
impl Connection {
43 44 45 46 47
    pub fn new(
        query: Arc<Query>,
        stream: TcpStream,
        addr: SocketAddr,
    ) -> Connection {
48
        Connection {
49
            query,
50 51
            stream,
            addr,
52
            chan: SyncChannel::new(10),
53 54 55
        }
    }

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

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

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

98 99 100 101 102 103 104 105
    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(())
106 107
    }

108
    fn handle_replies(&mut self) -> Result<()> {
109
        let empty_params = json!([]);
Roman Zeyde's avatar
Roman Zeyde committed
110
        loop {
111
            let msg = self.chan.receiver().recv().chain_err(|| "channel closed")?;
112
            trace!("RPC {:?}", msg);
Roman Zeyde's avatar
Roman Zeyde committed
113 114 115
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
116 117 118 119 120
                    let reply = match (
                        cmd.get("method"),
                        cmd.get("params").unwrap_or_else(|| &empty_params),
                        cmd.get("id"),
                    ) {
Roman Zeyde's avatar
Roman Zeyde committed
121 122
                        (
                            Some(&Value::String(ref method)),
123
                            &Value::Array(ref params),
124
                            Some(ref id),
Roman Zeyde's avatar
Roman Zeyde committed
125 126 127
                        ) => self.handle_command(method, params, id)?,
                        _ => bail!("invalid command: {}", cmd),
                    };
128
                    self.send_values(&[reply])?
129
                }
130
                Message::Done => return Ok(()),
131
            }
Roman Zeyde's avatar
Roman Zeyde committed
132 133 134
        }
    }

135
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
136
        loop {
137
            let mut line = Vec::<u8>::new();
Roman Zeyde's avatar
Roman Zeyde committed
138
            reader
139 140
                .read_until(b'\n', &mut line)
                .chain_err(|| "failed to read a request")?;
Roman Zeyde's avatar
Roman Zeyde committed
141
            if line.is_empty() {
142 143
                tx.send(Message::Done).chain_err(|| "channel closed")?;
                return Ok(());
Roman Zeyde's avatar
Roman Zeyde committed
144
            } else {
145 146 147 148 149
                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)
                }
150
                match String::from_utf8(line) {
Roman Zeyde's avatar
Roman Zeyde committed
151 152
                    Ok(req) => tx
                        .send(Message::Request(req))
153 154 155
                        .chain_err(|| "channel closed")?,
                    Err(err) => {
                        let _ = tx.send(Message::Done);
156
                        bail!("invalid UTF8: {}", err)
157 158
                    }
                }
Roman Zeyde's avatar
Roman Zeyde committed
159 160 161 162
            }
        }
    }

163
    pub fn run(mut self) {
164
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
165
        let tx = self.chan.sender();
166
        let child = spawn_thread("reader", || Connection::handle_requests(reader, tx));
167
        if let Err(e) = self.handle_replies() {
168 169 170 171 172 173
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
174
        debug!("[{}] shutting down connection", self.addr);
175
        let _ = self.stream.shutdown(Shutdown::Both);
176 177
        if let Err(err) = child.join().expect("receiver panicked") {
            error!("[{}] receiver failed: {}", self.addr, err);
178
        }
179 180 181
    }
}

kenshin-samourai's avatar
kenshin-samourai committed
182 183 184
//
// Messages supported by the RPC API
//
185
#[derive(Debug)]
186 187 188 189 190
pub enum Message {
    Request(String),
    Done,
}

kenshin-samourai's avatar
kenshin-samourai committed
191 192 193
//
// RPC server
//
194
pub struct RPC {
Roman Zeyde's avatar
Roman Zeyde committed
195
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
196 197 198
}

impl RPC {
199
    fn start_acceptor(addr: SocketAddr) -> Channel<Option<(TcpStream, SocketAddr)>> {
Roman Zeyde's avatar
Roman Zeyde committed
200
        let chan = Channel::unbounded();
201
        let acceptor = chan.sender();
202
        spawn_thread("acceptor", move || {
Roman Zeyde's avatar
Roman Zeyde committed
203 204
            let listener =
                TcpListener::bind(addr).unwrap_or_else(|e| panic!("bind({}) failed: {}", addr, e));
205
            info!(
kenshin-samourai's avatar
kenshin-samourai committed
206
                "Indexer RPC server running on {} (protocol {})",
207 208
                addr, PROTOCOL_VERSION
            );
209 210
            loop {
                let (stream, addr) = listener.accept().expect("accept failed");
Roman Zeyde's avatar
Roman Zeyde committed
211 212 213
                stream
                    .set_nonblocking(false)
                    .expect("failed to set connection as blocking");
214
                acceptor.send(Some((stream, addr))).expect("send failed");
215 216 217 218 219
            }
        });
        chan
    }

220
    pub fn start(addr: SocketAddr, query: Arc<Query>) -> RPC {
Roman Zeyde's avatar
Roman Zeyde committed
221
        RPC {
Roman Zeyde's avatar
Roman Zeyde committed
222
            server: Some(spawn_thread("rpc", move || {
223 224 225 226 227
                let senders = Arc::new(Mutex::new(HashMap::<i32, SyncSender<Message>>::new()));
                let handles = Arc::new(Mutex::new(
                    HashMap::<i32, std::thread::JoinHandle<()>>::new(),
                ));

228
                let acceptor = RPC::start_acceptor(addr);
229
                let mut handle_count = 0;
kenshin-samourai's avatar
kenshin-samourai committed
230

231
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                    let handle_id = handle_count;
                    handle_count += 1;
                    // explicitely scope the shadowed variables for the new thread
                    let handle: thread::JoinHandle<()> = {
                        let query = Arc::clone(&query);
                        let senders = Arc::clone(&senders);
                        let handles = Arc::clone(&handles);

                        spawn_thread("peer", move || {
                            info!("[{}] connected peer #{}", addr, handle_id);
                            let conn = Connection::new(query, stream, addr);
                            senders
                                .lock()
                                .unwrap()
                                .insert(handle_id, conn.chan.sender());
                            conn.run();
                            info!("[{}] disconnected peer #{}", addr, handle_id);
                            senders.lock().unwrap().remove(&handle_id);
                            handles.lock().unwrap().remove(&handle_id);
                        })
                    };

                    handles.lock().unwrap().insert(handle_id, handle);
255
                }
kenshin-samourai's avatar
kenshin-samourai committed
256

257
                trace!("closing {} RPC connections", senders.lock().unwrap().len());
258
                for sender in senders.lock().unwrap().values() {
259 260
                    let _ = sender.send(Message::Done);
                }
kenshin-samourai's avatar
kenshin-samourai committed
261

262 263 264 265 266
                trace!("waiting for {} RPC handling threads", handles.lock().unwrap().len());
                for (_, handle) in handles.lock().unwrap().drain() {
                    if let Err(e) = handle.join() {
                        warn!("failed to join thread: {:?}", e);
                    }
267
                }
kenshin-samourai's avatar
kenshin-samourai committed
268

Roman Zeyde's avatar
Roman Zeyde committed
269
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
270
            })),
Roman Zeyde's avatar
Roman Zeyde committed
271
        }
272
    }
Roman Zeyde's avatar
Roman Zeyde committed
273
}
274

Roman Zeyde's avatar
Roman Zeyde committed
275 276
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
277
        trace!("stop accepting new RPCs");
Roman Zeyde's avatar
Roman Zeyde committed
278 279 280
        if let Some(handle) = self.server.take() {
            handle.join().unwrap();
        }
Roman Zeyde's avatar
Roman Zeyde committed
281
        trace!("RPC server is stopped");
282
    }
Roman Zeyde's avatar
Roman Zeyde committed
283
}