query.rs 13.9 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
use crypto::digest::Digest;
use crypto::sha2::Sha256;
7
use lru::LruCache;
8
use std::collections::HashMap;
9
use std::sync::{Arc, Mutex, RwLock};
10

11 12
use app::App;
use index::{compute_script_hash, TxInRow, TxOutRow, TxRow};
13
use mempool::Tracker;
14
use metrics::Metrics;
15
use serde_json::Value;
16
use store::{ReadStore, Row};
17
use util::{FullHash, HashPrefix, HeaderEntry};
18

Roman Zeyde's avatar
Roman Zeyde committed
19
use errors::*;
Roman Zeyde's avatar
Roman Zeyde committed
20

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

28 29
type OutPoint = (Sha256dHash, usize); // (txid, output_index)

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

pub struct Status {
38 39 40 41
    confirmed: (Vec<FundingOutput>, Vec<SpendingInput>),
    mempool: (Vec<FundingOutput>, Vec<SpendingInput>),
}

42 43 44 45
fn calc_balance((funding, spending): &(Vec<FundingOutput>, Vec<SpendingInput>)) -> i64 {
    let funded: u64 = funding.iter().map(|output| output.value).sum();
    let spent: u64 = spending.iter().map(|input| input.value).sum();
    funded as i64 - spent as i64
Roman Zeyde's avatar
Roman Zeyde committed
46 47
}

48
impl Status {
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())
    }

57
    pub fn confirmed_balance(&self) -> i64 {
58 59 60
        calc_balance(&self.confirmed)
    }

61
    pub fn mempool_balance(&self) -> i64 {
62
        calc_balance(&self.mempool)
63 64
    }

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

79 80 81 82 83 84 85 86 87 88
    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);
            }
        }
89
        let mut outputs = outputs_map
90 91
            .into_iter()
            .map(|item| item.1) // a reference to unspent output
92 93 94
            .collect::<Vec<&FundingOutput>>();
        outputs.sort_unstable_by_key(|out| out.height);
        outputs
95 96
    }

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

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

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

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

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

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

159 160
pub struct TransactionCache {
    map: Mutex<LruCache<Sha256dHash, Transaction>>,
161 162 163
}

impl TransactionCache {
164
    pub fn new(capacity: usize) -> TransactionCache {
165
        TransactionCache {
166
            map: Mutex::new(LruCache::new(capacity)),
167 168 169 170 171 172 173
        }
    }

    fn get_or_else<F>(&self, txid: &Sha256dHash, load_txn_func: F) -> Result<Transaction>
    where
        F: FnOnce() -> Result<Transaction>,
    {
174
        if let Some(txn) = self.map.lock().unwrap().get(txid) {
175 176 177
            return Ok(txn.clone());
        }
        let txn = load_txn_func()?;
178
        self.map.lock().unwrap().put(*txid, txn.clone());
179 180 181 182
        Ok(txn)
    }
}

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

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

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

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

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

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

286 287 288 289
    fn mempool_status(
        &self,
        script_hash: &[u8],
        confirmed_funding: &[FundingOutput],
290
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
291 292
        let mut funding = vec![];
        let mut spending = vec![];
293
        let tracker = self.tracker.read().unwrap();
294 295
        let txid_prefixes = txids_by_script_hash(tracker.index(), script_hash);
        for t in self.load_txns_by_prefix(tracker.index(), txid_prefixes)? {
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> {
Roman Zeyde's avatar
Roman Zeyde committed
308 309
        let confirmed = self
            .confirmed_status(script_hash)
310
            .chain_err(|| "failed to get confirmed status")?;
Roman Zeyde's avatar
Roman Zeyde committed
311 312
        let mempool = self
            .mempool_status(script_hash, &confirmed.0)
313
            .chain_err(|| "failed to get mempool status")?;
314
        Ok(Status { confirmed, mempool })
315 316
    }

317
    fn lookup_confirmed_blockhash(
318 319 320
        &self,
        tx_hash: &Sha256dHash,
        block_height: Option<u32>,
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    ) -> Result<Option<Sha256dHash>> {
        let blockhash = if self.tracker.read().unwrap().get_txn(&tx_hash).is_some() {
            None // found in mempool (as unconfirmed transaction)
        } else {
            // Lookup in confirmed transactions' index
            let height = match block_height {
                Some(height) => height,
                None => {
                    txrow_by_txid(self.app.read_store(), &tx_hash)
                        .chain_err(|| format!("not indexed tx {}", tx_hash))?
                        .height
                }
            };
            let header = self
                .app
                .index()
                .get_header(height as usize)
                .chain_err(|| format!("missing header at height {}", height))?;
            Some(*header.hash())
340
        };
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        Ok(blockhash)
    }

    // Internal API for transaction retrieval
    fn load_txn(&self, tx_hash: &Sha256dHash, block_height: u32) -> Result<Transaction> {
        let blockhash = self.lookup_confirmed_blockhash(tx_hash, Some(block_height))?;
        self.app.daemon().gettransaction(tx_hash, blockhash)
    }

    // Public API for transaction retrieval (for Electrum RPC)
    pub fn get_transaction(&self, tx_hash: &Sha256dHash, verbose: bool) -> Result<Value> {
        let blockhash = self.lookup_confirmed_blockhash(tx_hash, /*block_height*/ None)?;
        self.app
            .daemon()
            .gettransaction_raw(tx_hash, blockhash, verbose)
356
    }
357

358 359 360 361 362 363
    pub fn get_headers(&self, heights: &[usize]) -> Vec<HeaderEntry> {
        let index = self.app.index();
        heights
            .iter()
            .filter_map(|height| index.get_header(*height))
            .collect()
364
    }
Roman Zeyde's avatar
Roman Zeyde committed
365

366
    pub fn get_best_header(&self) -> Result<HeaderEntry> {
367
        let last_header = self.app.index().best_header();
368
        Ok(last_header.chain_err(|| "no headers indexed")?.clone())
Roman Zeyde's avatar
Roman Zeyde committed
369
    }
Roman Zeyde's avatar
Roman Zeyde committed
370 371 372 373 374

    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
375
    ) -> Result<(Vec<Sha256dHash>, usize)> {
Roman Zeyde's avatar
Roman Zeyde committed
376 377
        let header_entry = self
            .app
378 379 380 381
            .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
382
        let mut txids: Vec<Sha256dHash> = block.txdata.iter().map(|tx| tx.txid()).collect();
383 384 385 386
        let pos = txids
            .iter()
            .position(|txid| txid == tx_hash)
            .chain_err(|| format!("missing txid {}", tx_hash))?;
Roman Zeyde's avatar
Roman Zeyde committed
387
        let mut merkle = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401
        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()
        }
402
        Ok((merkle, pos))
Roman Zeyde's avatar
Roman Zeyde committed
403
    }
404

405
    pub fn broadcast(&self, txn: &Transaction) -> Result<Sha256dHash> {
406
        self.app.daemon().broadcast(txn)
407 408
    }

Roman Zeyde's avatar
Roman Zeyde committed
409
    pub fn update_mempool(&self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
410
        self.tracker.write().unwrap().update(self.app.daemon())
411
    }
412

413
    /// Returns [vsize, fee_rate] pairs (measured in vbytes and satoshis).
414
    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
415 416 417
        self.tracker.read().unwrap().fee_histogram().clone()
    }

418 419 420 421 422 423 424 425 426 427 428 429 430
    // 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]
431
    }
432
}