query.rs 7.07 KB
Newer Older
Roman Zeyde's avatar
Roman Zeyde committed
1
use bitcoin::blockdata::block::{Block, BlockHeader};
2
use bitcoin::blockdata::transaction::Transaction;
Roman Zeyde's avatar
Roman Zeyde committed
3
use bitcoin::network::serialize::deserialize;
4 5
use bitcoin::util::hash::Sha256dHash;
use itertools::enumerate;
6
use std::sync::RwLock;
7

Roman Zeyde's avatar
Roman Zeyde committed
8
use daemon::Daemon;
9
use index::{compute_script_hash, Index, TxInRow, TxOutRow, TxRow};
10
use mempool::Tracker;
11
use store::Store;
12
use util::{HashPrefix, HeaderEntry};
13

Roman Zeyde's avatar
Roman Zeyde committed
14 15
error_chain!{}

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

pub struct SpendingInput {
    pub txn_id: Sha256dHash,
25
    pub height: i32,
Roman Zeyde's avatar
Roman Zeyde committed
26 27 28 29 30 31 32 33 34 35 36
    pub input_index: usize,
}

pub struct Status {
    pub balance: u64,
    pub funding: Vec<FundingOutput>,
    pub spending: Vec<SpendingInput>,
}

struct TxnHeight {
    txn: Transaction,
37
    height: i32,
Roman Zeyde's avatar
Roman Zeyde committed
38 39
}

Roman Zeyde's avatar
Roman Zeyde committed
40 41 42 43 44
fn merklize(left: Sha256dHash, right: Sha256dHash) -> Sha256dHash {
    let data = [&left[..], &right[..]].concat();
    Sha256dHash::from_data(&data)
}

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
impl Store {
    fn txrows_by_prefix(&self, txid_prefix: &HashPrefix) -> Vec<TxRow> {
        self.scan(&TxRow::filter(&txid_prefix))
            .iter()
            .map(|row| TxRow::from_row(row))
            .collect()
    }

    fn txids_by_script_hash(&self, script_hash: &[u8]) -> Vec<HashPrefix> {
        self.scan(&TxOutRow::filter(script_hash))
            .iter()
            .map(|row| TxOutRow::from_row(row).txid_prefix)
            .collect()
    }

    fn txids_by_funding_output(
        &self,
        txn_id: &Sha256dHash,
        output_index: usize,
    ) -> Vec<HashPrefix> {
        self.scan(&TxInRow::filter(&txn_id, output_index))
            .iter()
            .map(|row| TxInRow::from_row(row).txid_prefix)
            .collect()
    }
}

72 73 74 75 76 77 78
pub struct Query<'a> {
    store: &'a Store,
    daemon: &'a Daemon,
    index: &'a Index,
    tracker: RwLock<Tracker>,
}

79
// TODO: return errors instead of panics
80
impl<'a> Query<'a> {
81 82 83 84 85
    pub fn new(store: &'a Store, daemon: &'a Daemon, index: &'a Index) -> Query<'a> {
        Query {
            store,
            daemon,
            index,
86
            tracker: RwLock::new(Tracker::new()),
87
        }
88 89
    }

90 91 92 93
    pub fn daemon(&self) -> &Daemon {
        self.daemon
    }

Roman Zeyde's avatar
Roman Zeyde committed
94
    fn load_txns(&self, prefixes: Vec<HashPrefix>) -> Vec<TxnHeight> {
95 96
        let mut txns = Vec::new();
        for txid_prefix in prefixes {
97
            for tx_row in self.store.txrows_by_prefix(&txid_prefix) {
98
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
99
                let txn: Transaction = self.get_tx(&txid);
100 101
                txns.push(TxnHeight {
                    txn,
102
                    height: tx_row.height as i32,
103
                })
104 105 106 107 108
            }
        }
        txns
    }

Roman Zeyde's avatar
Roman Zeyde committed
109 110
    fn find_spending_input(&self, funding: &FundingOutput) -> Option<SpendingInput> {
        let spending_txns: Vec<TxnHeight> = self.load_txns(
111
            self.store
112
                .txids_by_funding_output(&funding.txn_id, funding.output_index),
113
        );
Roman Zeyde's avatar
Roman Zeyde committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        let mut spending_inputs = Vec::new();
        for t in &spending_txns {
            for (index, input) in enumerate(&t.txn.input) {
                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,
                        input_index: index,
                    })
                }
            }
        }
        assert!(spending_inputs.len() <= 1);
        if spending_inputs.len() == 1 {
            Some(spending_inputs.remove(0))
131 132 133 134 135
        } else {
            None
        }
    }

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
        let mut result = Vec::new();
        let txn_id = t.txn.txid();
        for (index, output) in enumerate(&t.txn.output) {
            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
    }

Roman Zeyde's avatar
Roman Zeyde committed
152 153 154 155 156 157 158
    pub fn status(&self, script_hash: &[u8]) -> Status {
        let mut status = Status {
            balance: 0,
            funding: vec![],
            spending: vec![],
        };

159
        for t in self.load_txns(self.store.txids_by_script_hash(script_hash)) {
160 161 162
            status
                .funding
                .extend(self.find_funding_outputs(&t, script_hash));
163
        }
Roman Zeyde's avatar
Roman Zeyde committed
164 165 166 167 168 169 170 171
        for funding_output in &status.funding {
            if let Some(spent) = self.find_spending_input(&funding_output) {
                status.spending.push(spent);
            } else {
                status.balance += funding_output.value;
            }
        }
        status
172
    }
173

174
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Transaction {
175
        self.daemon
176 177
            .gettransaction(tx_hash)
            .expect(&format!("failed to load tx {}", tx_hash))
178
    }
179

Roman Zeyde's avatar
Roman Zeyde committed
180
    pub fn get_headers(&self, heights: &[usize]) -> Vec<BlockHeader> {
181 182 183
        let headers_list = self.index.headers_list();
        let headers = headers_list.headers();
        let mut result = Vec::new();
Roman Zeyde's avatar
Roman Zeyde committed
184 185 186 187 188
        for height in heights {
            let header: &BlockHeader = match headers.get(*height) {
                Some(header) => header.header(),
                None => break,
            };
Roman Zeyde's avatar
Roman Zeyde committed
189
            result.push(*header);
190 191 192
        }
        result
    }
Roman Zeyde's avatar
Roman Zeyde committed
193 194 195 196 197

    pub fn get_best_header(&self) -> Option<HeaderEntry> {
        let header_list = self.index.headers_list();
        Some(header_list.headers().last()?.clone())
    }
Roman Zeyde's avatar
Roman Zeyde committed
198 199 200 201 202 203 204 205 206

    // TODO: add error-handling logic
    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
    ) -> Option<(Vec<Sha256dHash>, usize)> {
        let header_list = self.index.headers_list();
        let blockhash = header_list.headers().get(height)?.hash();
207
        let block: Block = self.daemon.getblock(&blockhash).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        let mut txids: Vec<Sha256dHash> = block.txdata.iter().map(|tx| tx.txid()).collect();
        let pos = txids.iter().position(|txid| txid == tx_hash)?;
        let mut merkle = Vec::new();
        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()
        }
        Some((merkle, pos))
    }
227

Roman Zeyde's avatar
Roman Zeyde committed
228
    pub fn update_mempool(&self) -> Result<()> {
229 230 231 232
        self.tracker
            .write()
            .unwrap()
            .update(self.daemon)
Roman Zeyde's avatar
Roman Zeyde committed
233
            .chain_err(|| "failed to update mempool")
234
    }
235 236 237 238

    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
        self.tracker.read().unwrap().fee_histogram()
    }
239
}