rpc.rs 14.3 KB
Newer Older
1 2
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::network::serialize::{deserialize, serialize};
3
use bitcoin::util::hash::Sha256dHash;
4
use error_chain::ChainedError;
5
use hex;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
6
use serde_json::{from_str, Number, 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::{sync_channel, Receiver, RecvTimeoutError, SyncSender};
Roman Zeyde's avatar
Roman Zeyde committed
11
use std::sync::Arc;
12
use std::thread;
13
use std::time::Duration;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
14

15
use query::Query;
Roman Zeyde's avatar
Roman Zeyde committed
16
use util::HeaderEntry;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
17

Roman Zeyde's avatar
Roman Zeyde committed
18
use errors::*;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
19

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

28 29 30 31 32 33
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)
}

34 35
fn jsonify_header(entry: &HeaderEntry) -> Value {
    let header = entry.header();
Roman Zeyde's avatar
Roman Zeyde committed
36
    json!({
37
        "block_height": entry.height(),
Roman Zeyde's avatar
Roman Zeyde committed
38 39 40 41 42 43 44 45 46
        "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
    })
}

47 48
struct Connection {
    query: Arc<Query>,
Roman Zeyde's avatar
Roman Zeyde committed
49
    last_header_entry: Option<HeaderEntry>,
50
    status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
51 52
    stream: TcpStream,
    addr: SocketAddr,
53 54
}

55 56
impl Connection {
    pub fn new(query: Arc<Query>, stream: TcpStream, addr: SocketAddr) -> Connection {
57
        Connection {
58
            query: query,
Roman Zeyde's avatar
Roman Zeyde committed
59
            last_header_entry: None, // disable header subscription for now
60
            status_hashes: HashMap::new(),
61 62
            stream,
            addr,
63 64 65 66
        }
    }

    fn blockchain_headers_subscribe(&mut self) -> Result<Value> {
67
        let entry = self.query.get_best_header()?;
Roman Zeyde's avatar
Roman Zeyde committed
68 69 70 71
        let hex_header = hex::encode(serialize(entry.header()).unwrap());
        let result = json!({"hex": hex_header, "height": entry.height()});
        self.last_header_entry = Some(entry);
        Ok(result)
72
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
73

74
    fn server_version(&self) -> Result<Value> {
75
        Ok(json!(["RustElectrum 0.1.0", "1.2"]))
76
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
77

78
    fn server_banner(&self) -> Result<Value> {
79
        Ok(json!("Welcome to RustElectrum Server!\n"))
80
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
81

82
    fn server_donation_address(&self) -> Result<Value> {
83
        Ok(Value::Null)
84
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
85

86 87 88
    fn server_peers_subscribe(&self) -> Result<Value> {
        Ok(json!([]))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
89

90
    fn mempool_get_fee_histogram(&self) -> Result<Value> {
91
        Ok(json!(self.query.get_fee_histogram()))
92
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
93

94 95 96 97
    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
98 99 100
        let headers: Vec<String> = self.query
            .get_headers(&heights)
            .into_iter()
101
            .map(|entry| hex::encode(&serialize(entry.header()).unwrap()))
Roman Zeyde's avatar
Roman Zeyde committed
102
            .collect();
103 104 105 106 107
        Ok(json!({
            "count": headers.len(),
            "hex": headers.join(""),
            "max": 2016,
        }))
108 109
    }

Roman Zeyde's avatar
Roman Zeyde committed
110
    fn blockchain_block_get_header(&self, params: &[Value]) -> Result<Value> {
111
        let height = usize_from_value(params.get(0), "missing height")?;
112 113 114 115 116 117
        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
118 119
    }

120
    fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
121 122
        let blocks_count = usize_from_value(params.get(0), "blocks_count")?;
        let fee_rate = self.query.estimate_fee(blocks_count); // in BTC/kB
123
        Ok(json!(fee_rate))
124
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
125

Roman Zeyde's avatar
Roman Zeyde committed
126
    fn blockchain_relayfee(&self) -> Result<Value> {
127
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
128 129
    }

130
    fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
131
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
132
        let status = self.query.status(&script_hash[..])?;
133
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
134 135
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
136
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
137

138
    fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
139
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
140
        let status = self.query.status(&script_hash[..])?;
141 142 143
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
144
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
145

Roman Zeyde's avatar
Roman Zeyde committed
146
    fn blockchain_scripthash_get_history(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
147
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
148
        let status = self.query.status(&script_hash[..])?;
Roman Zeyde's avatar
Roman Zeyde committed
149
        Ok(json!(Value::Array(
150 151
            status
                .history()
Roman Zeyde's avatar
Roman Zeyde committed
152 153 154 155
                .into_iter()
                .map(|item| json!({"height": item.0, "tx_hash": item.1.be_hex_string()}))
                .collect()
        )))
156
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
157

158 159 160 161 162
    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")?;
163
        let txid = self.query.broadcast(&tx)?;
164 165 166
        Ok(json!(txid.be_hex_string()))
    }

167
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
168
        // TODO: handle 'verbose' param
Roman Zeyde's avatar
Roman Zeyde committed
169
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
170
        let tx = self.query.load_txn(&tx_hash, /*blockhash=*/ None)?;
171
        Ok(json!(hex::encode(&serialize(&tx).unwrap())))
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
172 173
    }

Roman Zeyde's avatar
Roman Zeyde committed
174 175
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
176
        let height = usize_from_value(params.get(1), "height")?;
Roman Zeyde's avatar
Roman Zeyde committed
177 178 179 180 181 182 183 184 185 186 187
        let (merkle, pos) = self.query
            .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}))
188
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
189

190
    fn handle_command(&mut self, method: &str, params: &[Value], id: &Number) -> Result<Value> {
191 192 193 194 195 196 197
        let result = match method {
            "blockchain.headers.subscribe" => self.blockchain_headers_subscribe(),
            "server.version" => self.server_version(),
            "server.banner" => self.server_banner(),
            "server.donation_address" => self.server_donation_address(),
            "server.peers.subscribe" => self.server_peers_subscribe(),
            "mempool.get_fee_histogram" => self.mempool_get_fee_histogram(),
198
            "blockchain.block.headers" => self.blockchain_block_headers(&params),
Roman Zeyde's avatar
Roman Zeyde committed
199
            "blockchain.block.get_header" => self.blockchain_block_get_header(&params),
200
            "blockchain.estimatefee" => self.blockchain_estimatefee(&params),
Roman Zeyde's avatar
Roman Zeyde committed
201
            "blockchain.relayfee" => self.blockchain_relayfee(),
202 203 204
            "blockchain.scripthash.subscribe" => self.blockchain_scripthash_subscribe(&params),
            "blockchain.scripthash.get_balance" => self.blockchain_scripthash_get_balance(&params),
            "blockchain.scripthash.get_history" => self.blockchain_scripthash_get_history(&params),
205
            "blockchain.transaction.broadcast" => self.blockchain_transaction_broadcast(&params),
206 207 208
            "blockchain.transaction.get" => self.blockchain_transaction_get(&params),
            "blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(&params),
            &_ => bail!("unknown method {} {:?}", method, params),
209
        };
210
        // TODO: return application errors should be sent to the client
211 212 213
        Ok(match result {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(e) => {
Roman Zeyde's avatar
Roman Zeyde committed
214 215 216 217 218 219 220
                warn!(
                    "rpc #{} {} {:?} failed: {}",
                    id,
                    method,
                    params,
                    e.display_chain()
                );
221 222 223
                json!({"jsonrpc": "2.0", "id": id, "error": format!("{}", e)})
            }
        })
224 225
    }

Roman Zeyde's avatar
Roman Zeyde committed
226
    fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
227
        let mut result = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
228
        if let Some(ref mut last_entry) = self.last_header_entry {
229
            let entry = self.query.get_best_header()?;
Roman Zeyde's avatar
Roman Zeyde committed
230 231
            if *last_entry != entry {
                *last_entry = entry;
Roman Zeyde's avatar
Roman Zeyde committed
232 233
                let hex_header = hex::encode(serialize(last_entry.header()).unwrap());
                let header = json!({"hex": hex_header, "height": last_entry.height()});
Roman Zeyde's avatar
Roman Zeyde committed
234 235 236 237 238
                result.push(json!({
                    "jsonrpc": "2.0",
                    "method": "blockchain.headers.subscribe",
                    "params": [header]}));
            }
239 240
        }
        for (script_hash, status_hash) in self.status_hashes.iter_mut() {
241
            let status = self.query.status(&script_hash[..])?;
242
            let new_status_hash = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
243 244 245 246 247 248 249 250 251 252 253 254
            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;
        }
        Ok(result)
    }

255 256 257 258 259 260 261 262 263
    fn send_values(&mut self, values: &[Value]) -> Result<()> {
        for value in values {
            debug!("[{}] <- {}", self.addr, value);
            let line = value.to_string() + "\n";
            self.stream
                .write_all(line.as_bytes())
                .chain_err(|| format!("failed to send {}", value))?;
        }
        Ok(())
264 265 266
    }

    fn handle_replies(&mut self, chan: &Channel) -> Result<()> {
267
        let poll_duration = Duration::from_secs(5);
Roman Zeyde's avatar
Roman Zeyde committed
268 269
        let rx = chan.receiver();
        loop {
270 271 272 273 274
            let msg = match rx.recv_timeout(poll_duration) {
                Ok(msg) => msg,
                Err(RecvTimeoutError::Timeout) => Message::PeriodicUpdate,
                Err(RecvTimeoutError::Disconnected) => bail!("channel closed"),
            };
Roman Zeyde's avatar
Roman Zeyde committed
275 276 277
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
278
                    debug!("[{}] -> {}", self.addr, cmd);
Roman Zeyde's avatar
Roman Zeyde committed
279 280 281 282 283 284 285 286
                    let reply = match (cmd.get("method"), cmd.get("params"), cmd.get("id")) {
                        (
                            Some(&Value::String(ref method)),
                            Some(&Value::Array(ref params)),
                            Some(&Value::Number(ref id)),
                        ) => self.handle_command(method, params, id)?,
                        _ => bail!("invalid command: {}", cmd),
                    };
287
                    self.send_values(&[reply])?
288
                }
289
                Message::PeriodicUpdate => {
290 291 292
                    let values = self.update_subscriptions()
                        .chain_err(|| "failed to update subscriptions")?;
                    self.send_values(&values)?
Roman Zeyde's avatar
Roman Zeyde committed
293 294 295 296
                }
                Message::Done => {
                    debug!("done");
                    break;
297
                }
298
            }
Roman Zeyde's avatar
Roman Zeyde committed
299 300 301 302
        }
        Ok(())
    }

303
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) {
Roman Zeyde's avatar
Roman Zeyde committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317
        loop {
            let mut line = String::new();
            reader
                .read_line(&mut line)  // TODO: use .lines() iterator
                .expect("failed to read a request");
            if line.is_empty() {
                tx.send(Message::Done).expect("channel closed");
                break;
            } else {
                tx.send(Message::Request(line)).expect("channel closed");
            }
        }
    }

318
    pub fn run(mut self) {
319
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
320 321 322 323 324 325 326 327 328 329
        let chan = Channel::new();
        let tx = chan.sender();
        let child = thread::spawn(|| Connection::handle_requests(reader, tx));
        if let Err(e) = self.handle_replies(&chan) {
            error!(
                "[{}] connection handling failed: {}",
                self.addr,
                e.display_chain().to_string()
            );
        }
330
        info!("[{}] shutting down connection", self.addr);
331 332 333 334
        let _ = self.stream.shutdown(Shutdown::Both);
        if child.join().is_err() {
            error!("[{}] receiver panicked", self.addr);
        }
335 336 337 338 339
    }
}

pub enum Message {
    Request(String),
340
    PeriodicUpdate,
341 342 343 344 345 346 347 348 349 350
    Done,
}

pub struct Channel {
    tx: SyncSender<Message>,
    rx: Receiver<Message>,
}

impl Channel {
    pub fn new() -> Channel {
351
        let (tx, rx) = sync_channel(10);
352 353 354 355 356 357 358 359 360
        Channel { tx, rx }
    }

    pub fn sender(&self) -> SyncSender<Message> {
        self.tx.clone()
    }

    pub fn receiver(&self) -> &Receiver<Message> {
        &self.rx
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
361 362 363
    }
}

364 365
pub fn start(addr: &SocketAddr, query: Arc<Query>) -> thread::JoinHandle<()> {
    let listener = TcpListener::bind(addr).expect(&format!("bind({}) failed", addr));
366
    info!("RPC server running on {}", addr);
367 368
    thread::spawn(move || loop {
        let (stream, addr) = listener.accept().expect("accept failed");
369 370 371 372 373 374
        let query = query.clone();
        thread::spawn(move || {
            info!("[{}] connected peer", addr);
            Connection::new(query, stream, addr).run();
            info!("[{}] disconnected peer", addr);
        });
375
    })
Roman Zeyde's avatar
Roman Zeyde committed
376
}