rpc.rs 8.84 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::io::{BufRead, BufReader, Write};
6
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
7
use std::sync::mpsc::SyncSender;
8
use std::sync::{Arc, Mutex};
9
use std::thread;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
10

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

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

kenshin-samourai's avatar
kenshin-samourai committed
20 21 22
//
// Get a script hash from a given value
//
Roman Zeyde's avatar
Roman Zeyde committed
23
fn hash_from_value(val: Option<&Value>) -> Result<Sha256dHash> {
kenshin-samourai's avatar
kenshin-samourai committed
24
    // TODO: Sha256dHash should be a generic hash-container (since script hash is single SHA256)
Roman Zeyde's avatar
Roman Zeyde committed
25
    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)
}

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

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

55
    fn server_version(&self) -> Result<Value> {
56
        Ok(json!([
57
            format!("addrindexrs {}", ADDRINDEXRS_VERSION),
58 59
            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()
kenshin-samourai's avatar
kenshin-samourai committed
69
                .map(|item| json!({"tx_hash": item.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
    }

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

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

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

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

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

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

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

219
    pub fn start(addr: SocketAddr, query: Arc<Query>) -> RPC {
Roman Zeyde's avatar
Roman Zeyde committed
220
        RPC {
Roman Zeyde's avatar
Roman Zeyde committed
221
            server: Some(spawn_thread("rpc", move || {
222 223
                let senders = Arc::new(Mutex::new(Vec::<SyncSender<Message>>::new()));
                let acceptor = RPC::start_acceptor(addr);
224
                let mut children = vec![];
kenshin-samourai's avatar
kenshin-samourai committed
225

226 227 228
                while let Some((stream, addr)) = acceptor.receiver().recv().unwrap() {
                    let query = query.clone();
                    let senders = senders.clone();
229
                    children.push(spawn_thread("peer", move || {
230
                        info!("[{}] connected peer", addr);
231
                        let conn = Connection::new(query, stream, addr);
232 233 234
                        senders.lock().unwrap().push(conn.chan.sender());
                        conn.run();
                        info!("[{}] disconnected peer", addr);
235 236
                    }));
                }
kenshin-samourai's avatar
kenshin-samourai committed
237

238
                trace!("closing {} RPC connections", senders.lock().unwrap().len());
239 240 241
                for sender in senders.lock().unwrap().iter() {
                    let _ = sender.send(Message::Done);
                }
kenshin-samourai's avatar
kenshin-samourai committed
242

243
                trace!("waiting for {} RPC handling threads", children.len());
244 245
                for child in children {
                    let _ = child.join();
246
                }
kenshin-samourai's avatar
kenshin-samourai committed
247

Roman Zeyde's avatar
Roman Zeyde committed
248
                trace!("RPC connections are closed");
Roman Zeyde's avatar
Roman Zeyde committed
249
            })),
Roman Zeyde's avatar
Roman Zeyde committed
250
        }
251
    }
Roman Zeyde's avatar
Roman Zeyde committed
252
}
253

Roman Zeyde's avatar
Roman Zeyde committed
254 255
impl Drop for RPC {
    fn drop(&mut self) {
Roman Zeyde's avatar
Roman Zeyde committed
256
        trace!("stop accepting new RPCs");
Roman Zeyde's avatar
Roman Zeyde committed
257 258 259
        if let Some(handle) = self.server.take() {
            handle.join().unwrap();
        }
Roman Zeyde's avatar
Roman Zeyde committed
260
        trace!("RPC server is stopped");
261
    }
Roman Zeyde's avatar
Roman Zeyde committed
262
}