query.rs 10.3 KB
Newer Older
1
use bitcoin::blockdata::block::Block;
2
use bitcoin::blockdata::transaction::Transaction;
Roman Zeyde's avatar
Roman Zeyde committed
3
use bitcoin::network::serialize::deserialize;
4
use bitcoin::util::hash::Sha256dHash;
5 6 7
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use std::collections::HashMap;
8
use std::sync::{Arc, RwLock};
9

10 11
use app::App;
use index::{compute_script_hash, TxInRow, TxOutRow, TxRow};
12
use mempool::Tracker;
13
use store::ReadStore;
14
use util::{FullHash, HashPrefix, HeaderEntry};
15

Roman Zeyde's avatar
Roman Zeyde committed
16
use errors::*;
Roman Zeyde's avatar
Roman Zeyde committed
17

18 19
struct FundingOutput {
    txn_id: Sha256dHash,
20
    height: u32,
21 22
    output_index: usize,
    value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
23 24
}

25 26
struct SpendingInput {
    txn_id: Sha256dHash,
27
    height: u32,
28
    value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
29 30 31
}

pub struct Status {
32 33 34 35 36
    confirmed: (Vec<FundingOutput>, Vec<SpendingInput>),
    mempool: (Vec<FundingOutput>, Vec<SpendingInput>),
}

fn calc_balance((funding, spending): &(Vec<FundingOutput>, Vec<SpendingInput>)) -> u64 {
Roman Zeyde's avatar
Roman Zeyde committed
37 38 39
    let funded_values = funding.iter().map(|output| output.value);
    let spent_values = spending.iter().map(|input| input.value);
    funded_values.sum::<u64>() - spent_values.sum::<u64>()
Roman Zeyde's avatar
Roman Zeyde committed
40 41
}

42
impl Status {
43 44 45 46 47 48 49 50 51 52 53 54 55 56
    fn funding(&self) -> impl Iterator<Item = &FundingOutput> {
        self.confirmed.0.iter().chain(self.mempool.0.iter())
    }

    fn spending(&self) -> impl Iterator<Item = &SpendingInput> {
        self.confirmed.1.iter().chain(self.mempool.1.iter())
    }

    pub fn confirmed_balance(&self) -> u64 {
        calc_balance(&self.confirmed)
    }

    pub fn mempool_balance(&self) -> u64 {
        calc_balance(&self.mempool)
57 58
    }

59 60
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
61
        for f in self.funding() {
62
            txns_map.insert(f.txn_id, f.height as i32);
63
        }
64
        for s in self.spending() {
65
            txns_map.insert(s.txn_id, s.height as i32);
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        }
        let mut txns: Vec<(i32, Sha256dHash)> =
            txns_map.into_iter().map(|item| (item.1, item.0)).collect();
        txns.sort();
        txns
    }

    pub fn hash(&self) -> Option<FullHash> {
        let txns = self.history();
        if txns.is_empty() {
            None
        } else {
            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)
        }
    }
}

Roman Zeyde's avatar
Roman Zeyde committed
90 91
struct TxnHeight {
    txn: Transaction,
92
    height: u32,
Roman Zeyde's avatar
Roman Zeyde committed
93 94
}

Roman Zeyde's avatar
Roman Zeyde committed
95 96 97 98 99
fn merklize(left: Sha256dHash, right: Sha256dHash) -> Sha256dHash {
    let data = [&left[..], &right[..]].concat();
    Sha256dHash::from_data(&data)
}

100 101
// TODO: the 3 functions below can be part of ReadStore.
fn txrows_by_prefix(store: &ReadStore, txid_prefix: &HashPrefix) -> Vec<TxRow> {
102 103 104 105 106 107
    store
        .scan(&TxRow::filter(&txid_prefix))
        .iter()
        .map(|row| TxRow::from_row(row))
        .collect()
}
108

109
fn txids_by_script_hash(store: &ReadStore, script_hash: &[u8]) -> Vec<HashPrefix> {
110 111 112 113 114 115
    store
        .scan(&TxOutRow::filter(script_hash))
        .iter()
        .map(|row| TxOutRow::from_row(row).txid_prefix)
        .collect()
}
116

117
fn txids_by_funding_output(
118
    store: &ReadStore,
119 120 121 122 123 124 125 126
    txn_id: &Sha256dHash,
    output_index: usize,
) -> Vec<HashPrefix> {
    store
        .scan(&TxInRow::filter(&txn_id, output_index))
        .iter()
        .map(|row| TxInRow::from_row(row).txid_prefix)
        .collect()
127 128
}

129 130
pub struct Query {
    app: Arc<App>,
131 132 133
    tracker: RwLock<Tracker>,
}

134 135
impl Query {
    pub fn new(app: Arc<App>) -> Query {
136
        Query {
137
            app,
138
            tracker: RwLock::new(Tracker::new()),
139
        }
140 141
    }

142 143 144 145 146
    fn load_txns_by_prefix(
        &self,
        store: &ReadStore,
        prefixes: Vec<HashPrefix>,
    ) -> Result<Vec<TxnHeight>> {
Roman Zeyde's avatar
Roman Zeyde committed
147
        let mut txns = vec![];
148
        for txid_prefix in prefixes {
149
            for tx_row in txrows_by_prefix(store, &txid_prefix) {
150
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
151
                let txn: Transaction = self.get_tx(&txid)?;
152 153
                txns.push(TxnHeight {
                    txn,
154
                    height: tx_row.height,
155
                })
156 157
            }
        }
158
        Ok(txns)
159 160
    }

161 162 163 164
    fn find_spending_input(
        &self,
        store: &ReadStore,
        funding: &FundingOutput,
165
    ) -> Result<Option<SpendingInput>> {
166
        let spending_txns: Vec<TxnHeight> = self.load_txns_by_prefix(
167
            store,
168
            txids_by_funding_output(store, &funding.txn_id, funding.output_index),
169
        )?;
Roman Zeyde's avatar
Roman Zeyde committed
170
        let mut spending_inputs = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
171
        for t in &spending_txns {
172
            for input in t.txn.input.iter() {
Roman Zeyde's avatar
Roman Zeyde committed
173 174 175 176 177 178
                if input.prev_hash == funding.txn_id
                    && input.prev_index == funding.output_index as u32
                {
                    spending_inputs.push(SpendingInput {
                        txn_id: t.txn.txid(),
                        height: t.height,
179
                        value: funding.value,
Roman Zeyde's avatar
Roman Zeyde committed
180 181 182 183 184
                    })
                }
            }
        }
        assert!(spending_inputs.len() <= 1);
185
        Ok(if spending_inputs.len() == 1 {
Roman Zeyde's avatar
Roman Zeyde committed
186
            Some(spending_inputs.remove(0))
187 188
        } else {
            None
189
        })
190 191
    }

192
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
Roman Zeyde's avatar
Roman Zeyde committed
193
        let mut result = vec![];
194
        let txn_id = t.txn.txid();
Roman Zeyde's avatar
Roman Zeyde committed
195
        for (index, output) in t.txn.output.iter().enumerate() {
196 197 198 199 200 201 202 203 204 205 206 207
            if compute_script_hash(&output.script_pubkey[..]) == script_hash {
                result.push(FundingOutput {
                    txn_id: txn_id,
                    height: t.height,
                    output_index: index,
                    value: output.value,
                })
            }
        }
        result
    }

208 209 210 211
    fn confirmed_status(
        &self,
        script_hash: &[u8],
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
212 213
        let mut funding = vec![];
        let mut spending = vec![];
214
        for t in self.load_txns_by_prefix(
215 216
            self.app.read_store(),
            txids_by_script_hash(self.app.read_store(), script_hash),
217
        )? {
218
            funding.extend(self.find_funding_outputs(&t, script_hash));
219
        }
220
        for funding_output in &funding {
221
            if let Some(spent) = self.find_spending_input(self.app.read_store(), &funding_output)? {
222
                spending.push(spent);
223 224
            }
        }
225
        Ok((funding, spending))
226 227
    }

228 229 230 231
    fn mempool_status(
        &self,
        script_hash: &[u8],
        confirmed_funding: &[FundingOutput],
232
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
233 234
        let mut funding = vec![];
        let mut spending = vec![];
235
        let tracker = self.tracker.read().unwrap();
236
        for t in self.load_txns_by_prefix(
237 238
            tracker.index(),
            txids_by_script_hash(tracker.index(), script_hash),
239
        )? {
240
            funding.extend(self.find_funding_outputs(&t, script_hash));
241
        }
242
        // // TODO: dedup outputs (somehow) both confirmed and in mempool (e.g. reorg?)
243
        for funding_output in funding.iter().chain(confirmed_funding.iter()) {
244
            if let Some(spent) = self.find_spending_input(tracker.index(), &funding_output)? {
245
                spending.push(spent);
Roman Zeyde's avatar
Roman Zeyde committed
246 247
            }
        }
248
        Ok((funding, spending))
249
    }
250

251 252 253 254
    pub fn status(&self, script_hash: &[u8]) -> Result<Status> {
        let confirmed = self.confirmed_status(script_hash)?;
        let mempool = self.mempool_status(script_hash, &confirmed.0)?;
        Ok(Status { confirmed, mempool })
255 256
    }

257 258
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Result<Transaction> {
        self.app.daemon().gettransaction(tx_hash)
259
    }
260

261 262 263 264 265 266
    pub fn get_headers(&self, heights: &[usize]) -> Vec<HeaderEntry> {
        let index = self.app.index();
        heights
            .iter()
            .filter_map(|height| index.get_header(*height))
            .collect()
267
    }
Roman Zeyde's avatar
Roman Zeyde committed
268

269
    pub fn get_best_header(&self) -> Result<HeaderEntry> {
270
        let last_header = self.app.index().best_header();
271
        Ok(last_header.chain_err(|| "no headers indexed")?.clone())
Roman Zeyde's avatar
Roman Zeyde committed
272
    }
Roman Zeyde's avatar
Roman Zeyde committed
273 274 275 276 277

    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
278
    ) -> Result<(Vec<Sha256dHash>, usize)> {
279 280 281 282 283
        let header_entry = self.app
            .index()
            .get_header(height)
            .chain_err(|| format!("missing block #{}", height))?;
        let block: Block = self.app.daemon().getblock(&header_entry.hash())?;
Roman Zeyde's avatar
Roman Zeyde committed
284
        let mut txids: Vec<Sha256dHash> = block.txdata.iter().map(|tx| tx.txid()).collect();
285 286 287 288
        let pos = txids
            .iter()
            .position(|txid| txid == tx_hash)
            .chain_err(|| format!("missing txid {}", tx_hash))?;
Roman Zeyde's avatar
Roman Zeyde committed
289
        let mut merkle = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303
        let mut index = pos;
        while txids.len() > 1 {
            if txids.len() % 2 != 0 {
                let last = txids.last().unwrap().clone();
                txids.push(last);
            }
            index = if index % 2 == 0 { index + 1 } else { index - 1 };
            merkle.push(txids[index]);
            index = index / 2;
            txids = txids
                .chunks(2)
                .map(|pair| merklize(pair[0], pair[1]))
                .collect()
        }
304
        Ok((merkle, pos))
Roman Zeyde's avatar
Roman Zeyde committed
305
    }
306

307
    pub fn broadcast(&self, txn: &Transaction) -> Result<Sha256dHash> {
308
        self.app.daemon().broadcast(txn)
309 310
    }

Roman Zeyde's avatar
Roman Zeyde committed
311
    pub fn update_mempool(&self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
312
        self.tracker.write().unwrap().update(self.app.daemon())
313
    }
314

315
    /// Returns [vsize, fee_rate] pairs (measured in vbytes and satoshis).
316
    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
317 318 319
        self.tracker.read().unwrap().fee_histogram().clone()
    }

320 321 322 323 324 325 326 327 328 329 330 331 332
    // Fee rate [BTC/kB] to be confirmed in `blocks` from now.
    pub fn estimate_fee(&self, blocks: usize) -> f32 {
        let mut total_vsize = 0u32;
        let mut last_fee_rate = 0.0;
        let blocks_in_vbytes = (blocks * 1_000_000) as u32; // assume ~1MB blocks
        for (fee_rate, vsize) in self.tracker.read().unwrap().fee_histogram() {
            last_fee_rate = *fee_rate;
            total_vsize += vsize;
            if total_vsize >= blocks_in_vbytes {
                break; // under-estimate the fee rate a bit
            }
        }
        last_fee_rate * 1e-5 // [BTC/kB] = 10^5 [sat/B]
333
    }
334
}