rpc.rs 12.5 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
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
12

13
use query::Query;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
14 15 16

error_chain!{}

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

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

37
struct Connection<'a> {
38
    query: &'a Query<'a>,
39 40
    headers_subscribe: bool,
    status_hashes: HashMap<Sha256dHash, Value>, // ScriptHash -> StatusHash
41 42
    stream: TcpStream,
    addr: SocketAddr,
43 44
}

45 46 47
impl<'a> Connection<'a> {
    pub fn new(query: &'a Query, stream: TcpStream, addr: SocketAddr) -> Connection<'a> {
        Connection {
48 49 50
            query: query,
            headers_subscribe: false,
            status_hashes: HashMap::new(),
51 52
            stream,
            addr,
53 54 55 56
        }
    }

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

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

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

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

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

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

84 85 86 87 88
    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
89 90 91 92 93 94
        let headers: Vec<String> = self.query
            .get_headers(&heights)
            .into_iter()
            .map(|x| hex::encode(&serialize(&x).unwrap()))
            .collect();
        Ok(json!(headers.join("")))
95 96
    }

Roman Zeyde's avatar
Roman Zeyde committed
97 98 99 100
    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]);
101
        Ok(json!(jsonify_header(&headers[0], height)))
Roman Zeyde's avatar
Roman Zeyde committed
102 103
    }

104
    fn blockchain_estimatefee(&self, _params: &[Value]) -> Result<Value> {
105
        Ok(json!(-1)) // see mempool_get_fee_histogram() instead.
106
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
107

Roman Zeyde's avatar
Roman Zeyde committed
108
    fn blockchain_relayfee(&self) -> Result<Value> {
109
        Ok(json!(0.0)) // allow sending transactions with any fee.
Roman Zeyde's avatar
Roman Zeyde committed
110 111
    }

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

120
    fn blockchain_scripthash_get_balance(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
121
        let script_hash = hash_from_value(params.get(0)).chain_err(|| "bad script_hash")?;
Roman Zeyde's avatar
Roman Zeyde committed
122
        let status = self.query.status(&script_hash[..]);
123
        Ok(json!({ "confirmed": status.balance() })) // TODO: "unconfirmed"
124
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
125

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

138 139 140 141 142 143 144 145 146 147 148 149
    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()))
    }

150
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
151
        // TODO: handle 'verbose' param
Roman Zeyde's avatar
Roman Zeyde committed
152
        let tx_hash = hash_from_value(params.get(0)).chain_err(|| "bad tx_hash")?;
153 154
        let tx = self.query.get_tx(&tx_hash);
        Ok(json!(hex::encode(&serialize(&tx).unwrap())))
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
155 156
    }

Roman Zeyde's avatar
Roman Zeyde committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    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}))
172
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
173

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

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

225 226 227 228 229 230 231 232 233
    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<()> {
Roman Zeyde's avatar
Roman Zeyde committed
234 235 236 237 238 239
        let rx = chan.receiver();
        loop {
            let msg = rx.recv().chain_err(|| "channel closed")?;
            match msg {
                Message::Request(line) => {
                    let cmd: Value = from_str(&line).chain_err(|| "invalid JSON format")?;
240
                    debug!("[{}] -> {}", self.addr, cmd);
Roman Zeyde's avatar
Roman Zeyde committed
241 242 243 244 245 246 247 248
                    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),
                    };
249
                    self.send_value(reply)?
250
                }
Roman Zeyde's avatar
Roman Zeyde committed
251 252 253 254 255
                Message::Block(blockhash) => {
                    debug!("blockhash found: {}", blockhash);
                    for update in self.update_subscriptions()
                        .chain_err(|| "failed to get updates")?
                    {
256
                        self.send_value(update)?
257
                    }
Roman Zeyde's avatar
Roman Zeyde committed
258 259 260 261
                }
                Message::Done => {
                    debug!("done");
                    break;
262
                }
263
            }
Roman Zeyde's avatar
Roman Zeyde committed
264 265 266 267
        }
        Ok(())
    }

268
    fn handle_requests(mut reader: BufReader<TcpStream>, tx: SyncSender<Message>) {
Roman Zeyde's avatar
Roman Zeyde committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282
        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");
            }
        }
    }

283 284
    pub fn run(mut self, chan: &Channel) {
        let reader = BufReader::new(self.stream.try_clone().expect("failed to clone TcpStream"));
285
        // TODO: figure out graceful shutting down and error logging.
Roman Zeyde's avatar
Roman Zeyde committed
286 287
        crossbeam::scope(|scope| {
            let tx = chan.sender();
288 289
            scope.spawn(|| Connection::handle_requests(reader, tx));
            self.handle_replies(chan).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
290
        });
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    }
}

pub enum Message {
    Request(String),
    Block(Sha256dHash),
    Done,
}

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

impl Channel {
    pub fn new() -> Channel {
307
        let (tx, rx) = sync_channel(10);
308 309 310 311 312 313 314 315 316
        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
317 318 319
    }
}

Roman Zeyde's avatar
Roman Zeyde committed
320
pub fn serve(addr: &str, query: &Query, chan: Channel) {
321 322
    let listener = TcpListener::bind(addr).unwrap();
    info!("RPC server running on {}", addr);
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
323 324 325
    loop {
        let (stream, addr) = listener.accept().unwrap();
        info!("[{}] connected peer", addr);
326
        Connection::new(query, stream, addr).run(&chan);
Roman Zeyde's avatar
Roman Zeyde committed
327 328 329
        info!("[{}] disconnected peer", addr);
    }
}