rpc.rs 10.1 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

63 64 65 66 67 68
    fn blockchain_scripthash_get_balance(&self, _params: &[Value]) -> Result<Value> {
        Ok(
            json!({ "confirmed": null, "unconfirmed": null }),
        )
    }

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

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

105 106 107 108 109 110 111 112
    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(())
113 114
    }

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

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

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

kenshin-samourai's avatar
kenshin-samourai committed
189 190 191
//
// Messages supported by the RPC API
//
192
#[derive(Debug)]
193 194 195 196 197
pub enum Message {
    Request(String),
    Done,
}

kenshin-samourai's avatar
kenshin-samourai committed
198 199 200
//
// RPC server
//
201
pub struct RPC {
Roman Zeyde's avatar
Roman Zeyde committed
202
    server: Option<thread::JoinHandle<()>>, // so we can join the server while dropping this ojbect
203 204 205
}

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

227
    pub fn start(addr: SocketAddr, query: Arc<Query>) -> RPC {
Roman Zeyde's avatar
Roman Zeyde committed
228
        RPC {
Roman Zeyde's avatar
Roman Zeyde committed
229
            server: Some(spawn_thread("rpc", move || {
230 231 232 233 234
                let senders = Arc::new(Mutex::new(HashMap::<i32, SyncSender<Message>>::new()));
                let handles = Arc::new(Mutex::new(
                    HashMap::<i32, std::thread::JoinHandle<()>>::new(),
                ));

235
                let acceptor = RPC::start_acceptor(addr);
236
                let mut handle_count = 0;
kenshin-samourai's avatar
kenshin-samourai committed
237

238
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                    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);
262
                }
kenshin-samourai's avatar
kenshin-samourai committed
263

264
                trace!("closing {} RPC connections", senders.lock().unwrap().len());
265
                for sender in senders.lock().unwrap().values() {
266 267
                    let _ = sender.send(Message::Done);
                }
kenshin-samourai's avatar
kenshin-samourai committed
268

269 270 271 272 273
                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);
                    }
274
                }
kenshin-samourai's avatar
kenshin-samourai committed
275

Roman Zeyde's avatar
Roman Zeyde committed
276
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
277
            })),
Roman Zeyde's avatar
Roman Zeyde committed
278
        }
279
    }
Roman Zeyde's avatar
Roman Zeyde committed
280
}
281

Roman Zeyde's avatar
Roman Zeyde committed
282 283
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
284
        trace!("stop accepting new RPCs");
Roman Zeyde's avatar
Roman Zeyde committed
285 286 287
        if let Some(handle) = self.server.take() {
            handle.join().unwrap();
        }
Roman Zeyde's avatar
Roman Zeyde committed
288
        trace!("RPC server is stopped");
289
    }
Roman Zeyde's avatar
Roman Zeyde committed
290
}