rpc.rs 13.1 KB
Newer Older
Roman Zeyde's avatar
Roman Zeyde committed
1
use bitcoin::blockdata::block::BlockHeader;
2 3
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::network::serialize::{deserialize, serialize};
4
use bitcoin::util::hash::Sha256dHash;
5
use crossbeam;
6
use hex;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
7
use serde_json::{from_str, Number, Value};
Roman Zeyde's avatar
Roman Zeyde committed
8
use std::collections::HashMap;
9
use std::io::{BufRead, BufReader, Write};
10
use std::net::{SocketAddr, TcpListener, TcpStream};
11 12
use std::sync::mpsc::{sync_channel, Receiver, RecvTimeoutError, SyncSender};
use std::time::Duration;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
13

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

error_chain!{}

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

27
fn jsonify_header(header: &BlockHeader, height: usize) -> Value {
Roman Zeyde's avatar
Roman Zeyde committed
28 29 30 31 32 33 34 35 36 37 38
    json!({
        "block_height": height,
        "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
    })
}

39
struct Connection<'a> {
40
    query: &'a Query<'a>,
Roman Zeyde's avatar
Roman Zeyde committed
41
    last_header_entry: Option<HeaderEntry>,
42
    status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
43 44
    stream: TcpStream,
    addr: SocketAddr,
45 46
}

47 48 49
impl<'a> Connection<'a> {
    pub fn new(query: &'a Query, stream: TcpStream, addr: SocketAddr) -> Connection<'a> {
        Connection {
50
            query: query,
Roman Zeyde's avatar
Roman Zeyde committed
51
            last_header_entry: None, // disable header subscription for now
52
            status_hashes: HashMap::new(),
53 54
            stream,
            addr,
55 56 57 58
        }
    }

    fn blockchain_headers_subscribe(&mut self) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
59 60 61
        let entry = self.query
            .get_best_header()
            .chain_err(|| "no headers found")?;
Roman Zeyde's avatar
Roman Zeyde committed
62
        self.last_header_entry = Some(entry.clone());
63
        Ok(jsonify_header(entry.header(), entry.height()))
64
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
65

66
    fn server_version(&self) -> Result<Value> {
67
        Ok(json!(["RustElectrum 0.1.0", "1.2"]))
68
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
69

70
    fn server_banner(&self) -> Result<Value> {
71
        Ok(json!("Welcome to RustElectrum Server!\n"))
72
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
73

74
    fn server_donation_address(&self) -> Result<Value> {
75
        Ok(Value::Null)
76
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
77

78 79 80
    fn server_peers_subscribe(&self) -> Result<Value> {
        Ok(json!([]))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
81

82
    fn mempool_get_fee_histogram(&self) -> Result<Value> {
83
        Ok(json!(self.query.get_fee_histogram()))
84
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
85

86 87 88 89 90
    fn blockchain_block_get_chunk(&self, params: &[Value]) -> Result<Value> {
        const CHUNK_SIZE: usize = 2016;
        let index = params.get(0).chain_err(|| "missing index")?;
        let index = index.as_u64().chain_err(|| "non-number index")? as usize;
        let heights: Vec<usize> = (0..CHUNK_SIZE).map(|h| index * CHUNK_SIZE + h).collect();
Roman Zeyde's avatar
Roman Zeyde committed
91 92 93 94 95 96
        let headers: Vec<String> = self.query
            .get_headers(&heights)
            .into_iter()
            .map(|x| hex::encode(&serialize(&x).unwrap()))
            .collect();
        Ok(json!(headers.join("")))
97 98
    }

Roman Zeyde's avatar
Roman Zeyde committed
99 100 101 102
    fn blockchain_block_get_header(&self, params: &[Value]) -> Result<Value> {
        let height = params.get(0).chain_err(|| "missing height")?;
        let height = height.as_u64().chain_err(|| "non-number height")? as usize;
        let headers = self.query.get_headers(&vec![height]);
103
        Ok(json!(jsonify_header(&headers[0], height)))
Roman Zeyde's avatar
Roman Zeyde committed
104 105
    }

106 107 108 109 110
    fn blockchain_estimatefee(&self, params: &[Value]) -> Result<Value> {
        let blocks = params.get(0).chain_err(|| "missing blocks")?;
        let blocks = blocks.as_u64().chain_err(|| "non-number blocks")? as usize;
        let fee_rate = self.query.estimate_fee(blocks); // in BTC/kB
        Ok(json!(fee_rate))
111
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
112

Roman Zeyde's avatar
Roman Zeyde committed
113
    fn blockchain_relayfee(&self) -> Result<Value> {
114
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
115 116
    }

117
    fn blockchain_scripthash_subscribe(&mut self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
118
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
119
        let status = self.query.status(&script_hash[..]);
120
        let result = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
121 122
        self.status_hashes.insert(script_hash, result.clone());
        Ok(result)
123
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
124

125
    fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
126
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
127
        let status = self.query.status(&script_hash[..]);
128 129 130
        Ok(
            json!({ "confirmed": status.confirmed_balance(), "unconfirmed": status.mempool_balance() }),
        )
131
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
132

Roman Zeyde's avatar
Roman Zeyde committed
133
    fn blockchain_scripthash_get_history(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
134
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
135 136
        let status = self.query.status(&script_hash[..]);
        Ok(json!(Value::Array(
137 138
            status
                .history()
Roman Zeyde's avatar
Roman Zeyde committed
139 140 141 142
                .into_iter()
                .map(|item| json!({"height": item.0, "tx_hash": item.1.be_hex_string()}))
                .collect()
        )))
143
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
144

145 146 147 148 149 150 151 152 153 154 155 156
    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")?;
        let txid = self.query
            .daemon()
            .broadcast(&tx)
            .chain_err(|| "broadcast failed")?;
        Ok(json!(txid.be_hex_string()))
    }

157
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
158
        // TODO: handle 'verbose' param
Roman Zeyde's avatar
Roman Zeyde committed
159
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
160 161
        let tx = self.query.get_tx(&tx_hash);
        Ok(json!(hex::encode(&serialize(&tx).unwrap())))
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
162 163
    }

Roman Zeyde's avatar
Roman Zeyde committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    fn blockchain_transaction_get_merkle(&self, params: &[Value]) -> Result<Value> {
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
        let height = params.get(1).chain_err(|| "missing height")?;
        let height = height.as_u64().chain_err(|| "non-number height")? as usize;
        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}))
179
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
180

181
    fn handle_command(&mut self, method: &str, params: &[Value], id: &Number) -> Result<Value> {
182 183 184 185 186 187 188
        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(),
189
            "blockchain.block.get_chunk" => self.blockchain_block_get_chunk(&params),
Roman Zeyde's avatar
Roman Zeyde committed
190
            "blockchain.block.get_header" => self.blockchain_block_get_header(&params),
191
            "blockchain.estimatefee" => self.blockchain_estimatefee(&params),
Roman Zeyde's avatar
Roman Zeyde committed
192
            "blockchain.relayfee" => self.blockchain_relayfee(),
193 194 195
            "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),
196
            "blockchain.transaction.broadcast" => self.blockchain_transaction_broadcast(&params),
197 198 199 200
            "blockchain.transaction.get" => self.blockchain_transaction_get(&params),
            "blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(&params),
            &_ => bail!("unknown method {} {:?}", method, params),
        }?;
201
        // TODO: return application errors should be sent to the client
Roman Zeyde's avatar
Roman Zeyde committed
202
        Ok(json!({"jsonrpc": "2.0", "id": id, "result": result}))
203 204
    }

Roman Zeyde's avatar
Roman Zeyde committed
205
    fn update_subscriptions(&mut self) -> Result<Vec<Value>> {
206
        let mut result = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
207
        if let Some(ref mut last_entry) = self.last_header_entry {
208 209 210
            let entry = self.query
                .get_best_header()
                .chain_err(|| "no headers found")?;
Roman Zeyde's avatar
Roman Zeyde committed
211 212 213 214 215 216 217 218
            if *last_entry != entry {
                *last_entry = entry;
                let header = jsonify_header(last_entry.header(), last_entry.height());
                result.push(json!({
                    "jsonrpc": "2.0",
                    "method": "blockchain.headers.subscribe",
                    "params": [header]}));
            }
219 220 221
        }
        for (script_hash, status_hash) in self.status_hashes.iter_mut() {
            let status = self.query.status(&script_hash[..]);
222
            let new_status_hash = status.hash().map_or(Value::Null, |h| json!(hex::encode(h)));
223 224 225 226 227 228 229 230 231 232 233 234
            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)
    }

235 236 237 238 239 240 241 242 243
    fn send_value(&mut self, v: Value) -> Result<()> {
        debug!("[{}] <- {}", self.addr, v);
        let line = v.to_string() + "\n";
        self.stream
            .write_all(line.as_bytes())
            .chain_err(|| format!("failed to send {}", v))
    }

    fn handle_replies(&mut self, chan: &Channel) -> Result<()> {
244
        let poll_duration = Duration::from_secs(5);
Roman Zeyde's avatar
Roman Zeyde committed
245 246
        let rx = chan.receiver();
        loop {
247 248 249 250 251
            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
252 253 254
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
255
                    debug!("[{}] -> {}", self.addr, cmd);
Roman Zeyde's avatar
Roman Zeyde committed
256 257 258 259 260 261 262 263
                    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),
                    };
264
                    self.send_value(reply)?
265
                }
266
                Message::PeriodicUpdate => {
Roman Zeyde's avatar
Roman Zeyde committed
267
                    for update in self.update_subscriptions()
268
                        .chain_err(|| "failed to update subscriptions")?
Roman Zeyde's avatar
Roman Zeyde committed
269
                    {
270
                        self.send_value(update)?
271
                    }
Roman Zeyde's avatar
Roman Zeyde committed
272 273 274 275
                }
                Message::Done => {
                    debug!("done");
                    break;
276
                }
277
            }
Roman Zeyde's avatar
Roman Zeyde committed
278 279 280 281
        }
        Ok(())
    }

282
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) {
Roman Zeyde's avatar
Roman Zeyde committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
        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");
            }
        }
    }

297
    pub fn run(mut self) {
298
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
Roman Zeyde's avatar
Roman Zeyde committed
299
        crossbeam::scope(|scope| {
300
            let chan = Channel::new();
Roman Zeyde's avatar
Roman Zeyde committed
301
            let tx = chan.sender();
302
            scope.spawn(|| Connection::handle_requests(reader, tx));
303
            self.handle_replies(&chan).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
304
        });
305 306 307 308 309
    }
}

pub enum Message {
    Request(String),
310
    PeriodicUpdate,
311 312 313 314 315 316 317 318 319 320
    Done,
}

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

impl Channel {
    pub fn new() -> Channel {
321
        let (tx, rx) = sync_channel(10);
322 323 324 325 326 327 328 329 330
        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
331 332 333
    }
}

334
pub fn serve(addr: &SocketAddr, query: &Query) {
335 336
    let listener = TcpListener::bind(addr).unwrap();
    info!("RPC server running on {}", addr);
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
337 338 339
    loop {
        let (stream, addr) = listener.accept().unwrap();
        info!("[{}] connected peer", addr);
340
        Connection::new(query, stream, addr).run();
Roman Zeyde's avatar
Roman Zeyde committed
341 342 343
        info!("[{}] disconnected peer", addr);
    }
}