rpc.rs 8.33 KB
Newer Older
1
use bitcoin::util::hash::Sha256dHash;
2
use itertools;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
3
use serde_json::{from_str, Number, Value};
Roman Zeyde's avatar
Roman Zeyde committed
4
use std::collections::HashMap;
5
use std::io::{BufRead, BufReader, Write};
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
6 7
use std::net::{SocketAddr, TcpListener, TcpStream};

Roman Zeyde's avatar
Roman Zeyde committed
8 9
use query::{Query, Status};
use index::FullHash;
10
use util;
Roman Zeyde's avatar
Roman Zeyde committed
11 12
use crypto::digest::Digest;
use crypto::sha2::Sha256;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
13 14 15

error_chain!{}

16
struct Handler<'a> {
17
    query: &'a Query<'a>,
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
18 19
}

Roman Zeyde's avatar
Roman Zeyde committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
// TODO: Sha256dHash should be a generic hash-container (since script hash is single SHA256)
fn hash_from_params(params: &[Value]) -> Result<Sha256dHash> {
    let script_hash = params.get(0).chain_err(|| "missing hash")?;
    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)
}

fn history_from_status(status: &Status) -> Vec<(u32, Sha256dHash)> {
    let mut txns_map = HashMap::<Sha256dHash, u32>::new();
    for f in &status.funding {
        txns_map.insert(f.txn_id, f.height);
    }
    for s in &status.spending {
        txns_map.insert(s.txn_id, s.height);
    }
    let mut txns: Vec<(u32, Sha256dHash)> =
        txns_map.into_iter().map(|item| (item.1, item.0)).collect();
    txns.sort();
    txns
}

fn hash_from_status(status: &Status) -> Option<FullHash> {
    let txns = history_from_status(status);
    if txns.is_empty() {
        return None;
    }

    let mut hash = FullHash::default();
    let mut sha2 = Sha256::new();
    for (height, txn_id) in txns {
        let part = format!("{}:{}:", txn_id.be_hex_string(), height);
        sha2.input(part.as_bytes());
    }
    sha2.result(&mut hash);
    Some(hash)
}

58 59
impl<'a> Handler<'a> {
    fn blockchain_headers_subscribe(&self) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
60 61 62 63 64 65 66 67 68 69 70 71 72
        let entry = self.query
            .get_best_header()
            .chain_err(|| "no headers found")?;
        let header = entry.header();
        Ok(json!({
            "block_height": entry.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
        }))
73
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
74

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

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

83 84 85
    fn server_donation_address(&self) -> Result<Value> {
        Ok(json!("No, thanks :)\n"))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
86

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

91 92 93
    fn mempool_get_fee_histogram(&self) -> Result<Value> {
        Ok(json!([])) // TODO: consult with actual mempool
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
94

95 96 97 98 99 100 101 102 103 104 105
    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();
        let headers = self.query.get_headers(&heights);
        let result = itertools::join(headers.into_iter().map(|x| util::hexlify(&x)), "");
        Ok(json!(result))
    }

    fn blockchain_estimatefee(&self, _params: &[Value]) -> Result<Value> {
106 107
        Ok(json!(1e-5)) // TODO: consult with actual mempool
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
108

Roman Zeyde's avatar
Roman Zeyde committed
109 110 111 112 113 114 115 116 117 118 119 120
    fn blockchain_relayfee(&self) -> Result<Value> {
        Ok(json!(1e-5)) // TODO: consult with actual node
    }

    fn blockchain_scripthash_subscribe(&self, params: &[Value]) -> Result<Value> {
        let script_hash = hash_from_params(&params).chain_err(|| "bad script_hash")?;
        let status = self.query.status(&script_hash[..]);

        Ok(match hash_from_status(&status) {
            Some(hash) => Value::String(util::hexlify(&hash)),
            None => Value::Null,
        })
121
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
122

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

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

140
    fn blockchain_transaction_get(&self, params: &[Value]) -> Result<Value> {
Roman Zeyde's avatar
Roman Zeyde committed
141
        // TODO: handle 'verbose' param
Roman Zeyde's avatar
Roman Zeyde committed
142
        let tx_hash = hash_from_params(params).chain_err(|| "bad tx_hash")?;
143
        let tx_hex = util::hexlify(&self.query.get_tx(&tx_hash));
144
        Ok(json!(tx_hex))
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
145 146
    }

147
    fn blockchain_transaction_get_merkle(&self, _params: &[Value]) -> Result<Value> {
148 149
        Ok(json!({"block_height": 123, "merkle": ["A", "B", "C"], "pos": 45}))
    }
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
150

151
    fn handle_command(&self, method: &str, params: &[Value], id: &Number) -> Result<Value> {
152 153 154 155 156 157 158
        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(),
159
            "blockchain.block.get_chunk" => self.blockchain_block_get_chunk(&params),
160
            "blockchain.estimatefee" => self.blockchain_estimatefee(&params),
Roman Zeyde's avatar
Roman Zeyde committed
161
            "blockchain.relayfee" => self.blockchain_relayfee(),
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 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),
            "blockchain.transaction.get" => self.blockchain_transaction_get(&params),
            "blockchain.transaction.get_merkle" => self.blockchain_transaction_get_merkle(&params),
            &_ => bail!("unknown method {} {:?}", method, params),
        }?;
        let reply = json!({"jsonrpc": "2.0", "id": id, "result": result});
        Ok(reply)
    }

    pub fn run(self, mut stream: TcpStream, addr: SocketAddr) -> Result<()> {
        let mut reader = BufReader::new(stream
            .try_clone()
            .chain_err(|| "failed to clone TcpStream")?);
        let mut line = String::new();

        loop {
            line.clear();
            reader
                .read_line(&mut line)
                .chain_err(|| "failed to read a request")?;
            if line.is_empty() {
                break;
            }
            let line = line.trim_right();
            let cmd: Value = from_str(line).chain_err(|| "invalid JSON format")?;

            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),
            };

            debug!("[{}] {} -> {}", addr, cmd, reply);
            let mut line = reply.to_string();
            line.push_str("\n");
            stream
                .write_all(line.as_bytes())
                .chain_err(|| "failed to send response")?;
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
205
        }
206
        Ok(())
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
207 208 209
    }
}

210
pub fn serve(addr: &str, query: &Query) {
211 212
    let listener = TcpListener::bind(addr).unwrap();
    info!("RPC server running on {}", addr);
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
213 214 215
    loop {
        let (stream, addr) = listener.accept().unwrap();
        info!("[{}] connected peer", addr);
216 217
        let handler = Handler { query };
        match handler.run(stream, addr) {
Roman Zeyde's avatar
WiP  
Roman Zeyde committed
218 219 220 221 222 223 224 225 226 227
            Ok(()) => info!("[{}] disconnected peer", addr),
            Err(ref e) => {
                error!("[{}] {}", addr, e);
                for e in e.iter().skip(1) {
                    error!("caused by: {}", e);
                }
            }
        }
    }
}