query.rs 12.2 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 metrics::Metrics;
14
use store::{ReadStore, Row};
15
use util::{FullHash, HashPrefix, HeaderEntry};
16

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

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

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

pub struct Status {
33 34 35 36 37
    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
38 39 40
    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
41 42
}

43
impl Status {
44 45 46 47 48 49 50 51 52 53 54 55 56 57
    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)
58 59
    }

60 61
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
62
        for f in self.funding() {
63
            txns_map.insert(f.txn_id, f.height as i32);
64
        }
65
        for s in self.spending() {
66
            txns_map.insert(s.txn_id, s.height as i32);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        }
        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
91 92
struct TxnHeight {
    txn: Transaction,
93
    height: u32,
Roman Zeyde's avatar
Roman Zeyde committed
94 95
}

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

101 102 103 104 105 106 107
// TODO: the functions below can be part of ReadStore.
fn txrow_by_txid(store: &ReadStore, txid: &Sha256dHash) -> Option<TxRow> {
    let key = TxRow::filter_full(&txid);
    let value = store.get(&key)?;
    Some(TxRow::from_row(&Row { key, value }))
}

108
fn txrows_by_prefix(store: &ReadStore, txid_prefix: &HashPrefix) -> Vec<TxRow> {
109
    store
110
        .scan(&TxRow::filter_prefix(&txid_prefix))
111 112 113 114
        .iter()
        .map(|row| TxRow::from_row(row))
        .collect()
}
115

116
fn txids_by_script_hash(store: &ReadStore, script_hash: &[u8]) -> Vec<HashPrefix> {
117 118 119 120 121 122
    store
        .scan(&TxOutRow::filter(script_hash))
        .iter()
        .map(|row| TxOutRow::from_row(row).txid_prefix)
        .collect()
}
123

124
fn txids_by_funding_output(
125
    store: &ReadStore,
126 127 128 129 130 131 132 133
    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()
134 135
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
struct TransactionCache {
    map: RwLock<HashMap<Sha256dHash, Transaction>>,
}

impl TransactionCache {
    fn new() -> TransactionCache {
        TransactionCache {
            map: RwLock::new(HashMap::new()),
        }
    }

    fn get_or_else<F>(&self, txid: &Sha256dHash, load_txn_func: F) -> Result<Transaction>
    where
        F: FnOnce() -> Result<Transaction>,
    {
        if let Some(txn) = self.map.read().unwrap().get(txid) {
            return Ok(txn.clone());
        }
        let txn = load_txn_func()?;
        self.map.write().unwrap().insert(*txid, txn.clone());
        Ok(txn)
    }
}

160 161
pub struct Query {
    app: Arc<App>,
162
    tracker: RwLock<Tracker>,
163
    tx_cache: TransactionCache,
164 165
}

166
impl Query {
167
    pub fn new(app: Arc<App>, metrics: &Metrics) -> Arc<Query> {
168
        Arc::new(Query {
169
            app,
170
            tracker: RwLock::new(Tracker::new(metrics)),
171
            tx_cache: TransactionCache::new(),
172
        })
173 174
    }

175 176 177 178 179
    fn load_txns_by_prefix(
        &self,
        store: &ReadStore,
        prefixes: Vec<HashPrefix>,
    ) -> Result<Vec<TxnHeight>> {
Roman Zeyde's avatar
Roman Zeyde committed
180
        let mut txns = vec![];
181
        for txid_prefix in prefixes {
182
            for tx_row in txrows_by_prefix(store, &txid_prefix) {
183
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
184 185
                let txn = self.tx_cache
                    .get_or_else(&txid, || self.load_txn(&txid, Some(tx_row.height)))?;
186 187
                txns.push(TxnHeight {
                    txn,
188
                    height: tx_row.height,
189
                })
190 191
            }
        }
192
        Ok(txns)
193 194
    }

195 196 197 198
    fn find_spending_input(
        &self,
        store: &ReadStore,
        funding: &FundingOutput,
199
    ) -> Result<Option<SpendingInput>> {
200
        let spending_txns: Vec<TxnHeight> = self.load_txns_by_prefix(
201
            store,
202
            txids_by_funding_output(store, &funding.txn_id, funding.output_index),
203
        )?;
Roman Zeyde's avatar
Roman Zeyde committed
204
        let mut spending_inputs = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
205
        for t in &spending_txns {
206
            for input in t.txn.input.iter() {
Roman Zeyde's avatar
Roman Zeyde committed
207 208 209 210 211 212
                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,
213
                        value: funding.value,
Roman Zeyde's avatar
Roman Zeyde committed
214 215 216 217 218
                    })
                }
            }
        }
        assert!(spending_inputs.len() <= 1);
219
        Ok(if spending_inputs.len() == 1 {
Roman Zeyde's avatar
Roman Zeyde committed
220
            Some(spending_inputs.remove(0))
221 222
        } else {
            None
223
        })
224 225
    }

226
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
Roman Zeyde's avatar
Roman Zeyde committed
227
        let mut result = vec![];
228
        let txn_id = t.txn.txid();
Roman Zeyde's avatar
Roman Zeyde committed
229
        for (index, output) in t.txn.output.iter().enumerate() {
230 231 232 233 234 235 236 237 238 239 240 241
            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
    }

242 243 244 245
    fn confirmed_status(
        &self,
        script_hash: &[u8],
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
246 247
        let mut funding = vec![];
        let mut spending = vec![];
248
        for t in self.load_txns_by_prefix(
249 250
            self.app.read_store(),
            txids_by_script_hash(self.app.read_store(), script_hash),
251
        )? {
252
            funding.extend(self.find_funding_outputs(&t, script_hash));
253
        }
254
        for funding_output in &funding {
255
            if let Some(spent) = self.find_spending_input(self.app.read_store(), &funding_output)? {
256
                spending.push(spent);
257 258
            }
        }
259
        Ok((funding, spending))
260 261
    }

262 263 264 265
    fn mempool_status(
        &self,
        script_hash: &[u8],
        confirmed_funding: &[FundingOutput],
266
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
267 268
        let mut funding = vec![];
        let mut spending = vec![];
269
        let tracker = self.tracker.read().unwrap();
270
        for t in self.load_txns_by_prefix(
271 272
            tracker.index(),
            txids_by_script_hash(tracker.index(), script_hash),
273
        )? {
274
            funding.extend(self.find_funding_outputs(&t, script_hash));
275
        }
276
        // // TODO: dedup outputs (somehow) both confirmed and in mempool (e.g. reorg?)
277
        for funding_output in funding.iter().chain(confirmed_funding.iter()) {
278
            if let Some(spent) = self.find_spending_input(tracker.index(), &funding_output)? {
279
                spending.push(spent);
Roman Zeyde's avatar
Roman Zeyde committed
280 281
            }
        }
282
        Ok((funding, spending))
283
    }
284

285
    pub fn status(&self, script_hash: &[u8]) -> Result<Status> {
286 287 288 289
        let confirmed = self.confirmed_status(script_hash)
            .chain_err(|| "failed to get confirmed status")?;
        let mempool = self.mempool_status(script_hash, &confirmed.0)
            .chain_err(|| "failed to get mempool status")?;
290
        Ok(Status { confirmed, mempool })
291 292
    }

293 294 295 296 297
    pub fn load_txn(
        &self,
        tx_hash: &Sha256dHash,
        block_height: Option<u32>,
    ) -> Result<Transaction> {
298
        if let Some(txn) = self.tracker.read().unwrap().get_txn(&tx_hash) {
299
            return Ok(txn); // found in mempool (as unconfirmed transaction)
300
        }
301 302 303 304 305 306 307 308
        let height = match block_height {
            Some(height) => height,
            None => {
                // Lookup in confirmed transactions' index
                txrow_by_txid(self.app.read_store(), &tx_hash)
                    .chain_err(|| format!("not indexed tx {}", tx_hash))?
                    .height
            }
309
        };
310 311 312 313 314 315
        let blockhash = *self.app
            .index()
            .get_header(height as usize)
            .chain_err(|| format!("missing header at height {}", height))?
            .hash();
        self.app.daemon().gettransaction(tx_hash, Some(blockhash))
316
    }
317

318 319 320 321 322 323
    pub fn get_headers(&self, heights: &[usize]) -> Vec<HeaderEntry> {
        let index = self.app.index();
        heights
            .iter()
            .filter_map(|height| index.get_header(*height))
            .collect()
324
    }
Roman Zeyde's avatar
Roman Zeyde committed
325

326
    pub fn get_best_header(&self) -> Result<HeaderEntry> {
327
        let last_header = self.app.index().best_header();
328
        Ok(last_header.chain_err(|| "no headers indexed")?.clone())
Roman Zeyde's avatar
Roman Zeyde committed
329
    }
Roman Zeyde's avatar
Roman Zeyde committed
330 331 332 333 334

    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
335
    ) -> Result<(Vec<Sha256dHash>, usize)> {
336 337 338 339 340
        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
341
        let mut txids: Vec<Sha256dHash> = block.txdata.iter().map(|tx| tx.txid()).collect();
342 343 344 345
        let pos = txids
            .iter()
            .position(|txid| txid == tx_hash)
            .chain_err(|| format!("missing txid {}", tx_hash))?;
Roman Zeyde's avatar
Roman Zeyde committed
346
        let mut merkle = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360
        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()
        }
361
        Ok((merkle, pos))
Roman Zeyde's avatar
Roman Zeyde committed
362
    }
363

364
    pub fn broadcast(&self, txn: &Transaction) -> Result<Sha256dHash> {
365
        self.app.daemon().broadcast(txn)
366 367
    }

Roman Zeyde's avatar
Roman Zeyde committed
368
    pub fn update_mempool(&self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
369
        self.tracker.write().unwrap().update(self.app.daemon())
370
    }
371

372
    /// Returns [vsize, fee_rate] pairs (measured in vbytes and satoshis).
373
    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
374 375 376
        self.tracker.read().unwrap().fee_histogram().clone()
    }

377 378 379 380 381 382 383 384 385 386 387 388 389
    // 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]
390
    }
391
}