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 73 74 75 76
        }
        let mut txns: Vec<(i32, Sha256dHash)> =
            txns_map.into_iter().map(|item| (item.1, item.0)).collect();
        txns.sort();
        txns
    }

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    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);
            }
        }
        outputs_map
            .into_iter()
            .map(|item| item.1) // a reference to unspent output
            .collect::<Vec<&FundingOutput>>()
        // TODO: sort the outputs by height
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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