query.rs 13 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 21 22 23
pub struct FundingOutput {
    pub txn_id: Sha256dHash,
    pub height: u32,
    pub output_index: usize,
    pub value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
24 25
}

26 27
type OutPoint = (Sha256dHash, usize); // (txid, output_index)

28 29
struct SpendingInput {
    txn_id: Sha256dHash,
30
    height: u32,
31
    funding_output: OutPoint,
32
    value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
33 34 35
}

pub struct Status {
36 37 38 39 40
    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
41 42 43
    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
44 45
}

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

63 64
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
65
        for f in self.funding() {
66
            txns_map.insert(f.txn_id, f.height as i32);
67
        }
68
        for s in self.spending() {
69
            txns_map.insert(s.txn_id, s.height as i32);
70 71 72
        }
        let mut txns: Vec<(i32, Sha256dHash)> =
            txns_map.into_iter().map(|item| (item.1, item.0)).collect();
73
        txns.sort_unstable();
74 75 76
        txns
    }

77 78 79 80 81 82 83 84 85 86
    pub fn unspent(&self) -> Vec<&FundingOutput> {
        let mut outputs_map = HashMap::<OutPoint, &FundingOutput>::new();
        for f in self.funding() {
            outputs_map.insert((f.txn_id, f.output_index), f);
        }
        for s in self.spending() {
            if let None = outputs_map.remove(&s.funding_output) {
                warn!("failed to remove {:?}", s.funding_output);
            }
        }
87
        let mut outputs = outputs_map
88 89
            .into_iter()
            .map(|item| item.1) // a reference to unspent output
90 91 92
            .collect::<Vec<&FundingOutput>>();
        outputs.sort_unstable_by_key(|out| out.height);
        outputs
93 94
    }

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    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
112 113
struct TxnHeight {
    txn: Transaction,
114
    height: u32,
Roman Zeyde's avatar
Roman Zeyde committed
115 116
}

Roman Zeyde's avatar
Roman Zeyde committed
117 118 119 120 121
fn merklize(left: Sha256dHash, right: Sha256dHash) -> Sha256dHash {
    let data = [&left[..], &right[..]].concat();
    Sha256dHash::from_data(&data)
}

122 123 124 125 126 127 128
// 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 }))
}

129
fn txrows_by_prefix(store: &ReadStore, txid_prefix: &HashPrefix) -> Vec<TxRow> {
130
    store
131
        .scan(&TxRow::filter_prefix(&txid_prefix))
132 133 134 135
        .iter()
        .map(|row| TxRow::from_row(row))
        .collect()
}
136

137
fn txids_by_script_hash(store: &ReadStore, script_hash: &[u8]) -> Vec<HashPrefix> {
138 139 140 141 142 143
    store
        .scan(&TxOutRow::filter(script_hash))
        .iter()
        .map(|row| TxOutRow::from_row(row).txid_prefix)
        .collect()
}
144

145
fn txids_by_funding_output(
146
    store: &ReadStore,
147 148 149 150 151 152 153 154
    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()
155 156
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
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)
    }
}

181 182
pub struct Query {
    app: Arc<App>,
183
    tracker: RwLock<Tracker>,
184
    tx_cache: TransactionCache,
185 186
}

187
impl Query {
188
    pub fn new(app: Arc<App>, metrics: &Metrics) -> Arc<Query> {
189
        Arc::new(Query {
190
            app,
191
            tracker: RwLock::new(Tracker::new(metrics)),
192
            tx_cache: TransactionCache::new(),
193
        })
194 195
    }

196 197 198 199 200
    fn load_txns_by_prefix(
        &self,
        store: &ReadStore,
        prefixes: Vec<HashPrefix>,
    ) -> Result<Vec<TxnHeight>> {
Roman Zeyde's avatar
Roman Zeyde committed
201
        let mut txns = vec![];
202
        for txid_prefix in prefixes {
203
            for tx_row in txrows_by_prefix(store, &txid_prefix) {
204
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
205 206
                let txn = self.tx_cache
                    .get_or_else(&txid, || self.load_txn(&txid, Some(tx_row.height)))?;
207 208
                txns.push(TxnHeight {
                    txn,
209
                    height: tx_row.height,
210
                })
211 212
            }
        }
213
        Ok(txns)
214 215
    }

216 217 218 219
    fn find_spending_input(
        &self,
        store: &ReadStore,
        funding: &FundingOutput,
220
    ) -> Result<Option<SpendingInput>> {
221
        let spending_txns: Vec<TxnHeight> = self.load_txns_by_prefix(
222
            store,
223
            txids_by_funding_output(store, &funding.txn_id, funding.output_index),
224
        )?;
Roman Zeyde's avatar
Roman Zeyde committed
225
        let mut spending_inputs = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
226
        for t in &spending_txns {
227
            for input in t.txn.input.iter() {
Roman Zeyde's avatar
Roman Zeyde committed
228 229 230 231 232 233
                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,
234
                        funding_output: (funding.txn_id, funding.output_index),
235
                        value: funding.value,
Roman Zeyde's avatar
Roman Zeyde committed
236 237 238 239 240
                    })
                }
            }
        }
        assert!(spending_inputs.len() <= 1);
241
        Ok(if spending_inputs.len() == 1 {
Roman Zeyde's avatar
Roman Zeyde committed
242
            Some(spending_inputs.remove(0))
243 244
        } else {
            None
245
        })
246 247
    }

248
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
Roman Zeyde's avatar
Roman Zeyde committed
249
        let mut result = vec![];
250
        let txn_id = t.txn.txid();
Roman Zeyde's avatar
Roman Zeyde committed
251
        for (index, output) in t.txn.output.iter().enumerate() {
252 253 254 255 256 257 258 259 260 261 262 263
            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
    }

264 265 266 267
    fn confirmed_status(
        &self,
        script_hash: &[u8],
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
268 269
        let mut funding = vec![];
        let mut spending = vec![];
270
        for t in self.load_txns_by_prefix(
271 272
            self.app.read_store(),
            txids_by_script_hash(self.app.read_store(), script_hash),
273
        )? {
274
            funding.extend(self.find_funding_outputs(&t, script_hash));
275
        }
276
        for funding_output in &funding {
277
            if let Some(spent) = self.find_spending_input(self.app.read_store(), &funding_output)? {
278
                spending.push(spent);
279 280
            }
        }
281
        Ok((funding, spending))
282 283
    }

284 285 286 287
    fn mempool_status(
        &self,
        script_hash: &[u8],
        confirmed_funding: &[FundingOutput],
288
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
289 290
        let mut funding = vec![];
        let mut spending = vec![];
291
        let tracker = self.tracker.read().unwrap();
292
        for t in self.load_txns_by_prefix(
293 294
            tracker.index(),
            txids_by_script_hash(tracker.index(), script_hash),
295
        )? {
296
            funding.extend(self.find_funding_outputs(&t, script_hash));
297
        }
298
        // // TODO: dedup outputs (somehow) both confirmed and in mempool (e.g. reorg?)
299
        for funding_output in funding.iter().chain(confirmed_funding.iter()) {
300
            if let Some(spent) = self.find_spending_input(tracker.index(), &funding_output)? {
301
                spending.push(spent);
Roman Zeyde's avatar
Roman Zeyde committed
302 303
            }
        }
304
        Ok((funding, spending))
305
    }
306

307
    pub fn status(&self, script_hash: &[u8]) -> Result<Status> {
308 309 310 311
        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")?;
312
        Ok(Status { confirmed, mempool })
313 314
    }

315 316 317 318 319
    pub fn load_txn(
        &self,
        tx_hash: &Sha256dHash,
        block_height: Option<u32>,
    ) -> Result<Transaction> {
320
        if let Some(txn) = self.tracker.read().unwrap().get_txn(&tx_hash) {
321
            return Ok(txn); // found in mempool (as unconfirmed transaction)
322
        }
323 324 325 326 327 328 329 330
        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
            }
331
        };
332 333 334 335 336 337
        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))
338
    }
339

340 341 342 343 344 345
    pub fn get_headers(&self, heights: &[usize]) -> Vec<HeaderEntry> {
        let index = self.app.index();
        heights
            .iter()
            .filter_map(|height| index.get_header(*height))
            .collect()
346
    }
Roman Zeyde's avatar
Roman Zeyde committed
347

348
    pub fn get_best_header(&self) -> Result<HeaderEntry> {
349
        let last_header = self.app.index().best_header();
350
        Ok(last_header.chain_err(|| "no headers indexed")?.clone())
Roman Zeyde's avatar
Roman Zeyde committed
351
    }
Roman Zeyde's avatar
Roman Zeyde committed
352 353 354 355 356

    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
357
    ) -> Result<(Vec<Sha256dHash>, usize)> {
358 359 360 361 362
        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
363
        let mut txids: Vec<Sha256dHash> = block.txdata.iter().map(|tx| tx.txid()).collect();
364 365 366 367
        let pos = txids
            .iter()
            .position(|txid| txid == tx_hash)
            .chain_err(|| format!("missing txid {}", tx_hash))?;
Roman Zeyde's avatar
Roman Zeyde committed
368
        let mut merkle = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382
        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()
        }
383
        Ok((merkle, pos))
Roman Zeyde's avatar
Roman Zeyde committed
384
    }
385

386
    pub fn broadcast(&self, txn: &Transaction) -> Result<Sha256dHash> {
387
        self.app.daemon().broadcast(txn)
388 389
    }

Roman Zeyde's avatar
Roman Zeyde committed
390
    pub fn update_mempool(&self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
391
        self.tracker.write().unwrap().update(self.app.daemon())
392
    }
393

394
    /// Returns [vsize, fee_rate] pairs (measured in vbytes and satoshis).
395
    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
396 397 398
        self.tracker.read().unwrap().fee_histogram().clone()
    }

399 400 401 402 403 404 405 406 407 408 409 410 411
    // 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]
412
    }
413
}