query.rs 8.1 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
use bitcoin::util::hash::Sha256dHash;
5 6 7
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use std::collections::HashMap;
8
use std::sync::RwLock;
9

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

Roman Zeyde's avatar
Roman Zeyde committed
16 17
error_chain!{}

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

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

pub struct Status {
32
    // TODO: make private
33 34 35
    balance: u64,
    funding: Vec<FundingOutput>,
    spending: Vec<SpendingInput>,
Roman Zeyde's avatar
Roman Zeyde committed
36 37
}

38
impl Status {
39 40 41 42
    pub fn balance(&self) -> u64 {
        self.balance
    }

43 44 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 72 73
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
        for f in &self.funding {
            txns_map.insert(f.txn_id, f.height);
        }
        for s in &self.spending {
            txns_map.insert(s.txn_id, s.height);
        }
        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
74 75
struct TxnHeight {
    txn: Transaction,
76
    height: i32,
Roman Zeyde's avatar
Roman Zeyde committed
77 78
}

Roman Zeyde's avatar
Roman Zeyde committed
79 80 81 82 83
fn merklize(left: Sha256dHash, right: Sha256dHash) -> Sha256dHash {
    let data = [&left[..], &right[..]].concat();
    Sha256dHash::from_data(&data)
}

84 85 86 87 88 89 90
fn txrows_by_prefix(store: &Store, txid_prefix: &HashPrefix) -> Vec<TxRow> {
    store
        .scan(&TxRow::filter(&txid_prefix))
        .iter()
        .map(|row| TxRow::from_row(row))
        .collect()
}
91

92 93 94 95 96 97 98
fn txids_by_script_hash(store: &Store, script_hash: &[u8]) -> Vec<HashPrefix> {
    store
        .scan(&TxOutRow::filter(script_hash))
        .iter()
        .map(|row| TxOutRow::from_row(row).txid_prefix)
        .collect()
}
99

100 101 102 103 104 105 106 107 108 109
fn txids_by_funding_output(
    store: &Store,
    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()
110 111
}

112 113 114 115 116 117 118
pub struct Query<'a> {
    store: &'a Store,
    daemon: &'a Daemon,
    index: &'a Index,
    tracker: RwLock<Tracker>,
}

119
// TODO: return errors instead of panics
120
impl<'a> Query<'a> {
121 122 123 124 125
    pub fn new(store: &'a Store, daemon: &'a Daemon, index: &'a Index) -> Query<'a> {
        Query {
            store,
            daemon,
            index,
126
            tracker: RwLock::new(Tracker::new()),
127
        }
128 129
    }

130 131 132 133
    pub fn daemon(&self) -> &Daemon {
        self.daemon
    }

Roman Zeyde's avatar
Roman Zeyde committed
134
    fn load_txns(&self, prefixes: Vec<HashPrefix>) -> Vec<TxnHeight> {
135 136
        let mut txns = Vec::new();
        for txid_prefix in prefixes {
137
            for tx_row in txrows_by_prefix(self.store, &txid_prefix) {
138
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
139
                let txn: Transaction = self.get_tx(&txid);
140 141
                txns.push(TxnHeight {
                    txn,
142
                    height: tx_row.height as i32,
143
                })
144 145 146 147 148
            }
        }
        txns
    }

Roman Zeyde's avatar
Roman Zeyde committed
149
    fn find_spending_input(&self, funding: &FundingOutput) -> Option<SpendingInput> {
150 151 152 153 154
        let spending_txns: Vec<TxnHeight> = self.load_txns(txids_by_funding_output(
            self.store,
            &funding.txn_id,
            funding.output_index,
        ));
Roman Zeyde's avatar
Roman Zeyde committed
155 156
        let mut spending_inputs = Vec::new();
        for t in &spending_txns {
Roman Zeyde's avatar
Roman Zeyde committed
157
            for (index, input) in t.txn.input.iter().enumerate() {
Roman Zeyde's avatar
Roman Zeyde committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171
                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))
172 173 174 175 176
        } else {
            None
        }
    }

177 178 179
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
        let mut result = Vec::new();
        let txn_id = t.txn.txid();
Roman Zeyde's avatar
Roman Zeyde committed
180
        for (index, output) in t.txn.output.iter().enumerate() {
181 182 183 184 185 186 187 188 189 190 191 192
            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
193 194 195 196 197 198 199
    pub fn status(&self, script_hash: &[u8]) -> Status {
        let mut status = Status {
            balance: 0,
            funding: vec![],
            spending: vec![],
        };

200
        for t in self.load_txns(txids_by_script_hash(self.store, script_hash)) {
201 202 203
            status
                .funding
                .extend(self.find_funding_outputs(&t, script_hash));
204
        }
Roman Zeyde's avatar
Roman Zeyde committed
205 206 207 208 209 210 211 212
        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
213
    }
214

215
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Transaction {
216
        self.daemon
217 218
            .gettransaction(tx_hash)
            .expect(&format!("failed to load tx {}", tx_hash))
219
    }
220

Roman Zeyde's avatar
Roman Zeyde committed
221
    pub fn get_headers(&self, heights: &[usize]) -> Vec<BlockHeader> {
222 223 224
        let headers_list = self.index.headers_list();
        let headers = headers_list.headers();
        let mut result = Vec::new();
Roman Zeyde's avatar
Roman Zeyde committed
225 226 227 228 229
        for height in heights {
            let header: &BlockHeader = match headers.get(*height) {
                Some(header) => header.header(),
                None => break,
            };
Roman Zeyde's avatar
Roman Zeyde committed
230
            result.push(*header);
231 232 233
        }
        result
    }
Roman Zeyde's avatar
Roman Zeyde committed
234 235 236 237 238

    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
239 240 241 242 243 244 245 246 247

    // 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();
248
        let block: Block = self.daemon.getblock(&blockhash).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        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))
    }
268

Roman Zeyde's avatar
Roman Zeyde committed
269
    pub fn update_mempool(&self) -> Result<()> {
270 271 272 273
        self.tracker
            .write()
            .unwrap()
            .update(self.daemon)
Roman Zeyde's avatar
Roman Zeyde committed
274
            .chain_err(|| "failed to update mempool")
275
    }
276 277 278 279

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