query.rs 6.27 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 6
use bitcoin::util::hash::Sha256dHash;
use itertools::enumerate;

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

pub struct Query<'a> {
    store: &'a Store,
    daemon: &'a Daemon,
15
    index: &'a Index,
16 17
}

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

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

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

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

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

47
// TODO: return errors instead of panics
48
impl<'a> Query<'a> {
49 50 51 52 53 54
    pub fn new(store: &'a Store, daemon: &'a Daemon, index: &'a Index) -> Query<'a> {
        Query {
            store,
            daemon,
            index,
        }
55 56
    }

Roman Zeyde's avatar
Roman Zeyde committed
57
    fn load_txns(&self, prefixes: Vec<HashPrefix>) -> Vec<TxnHeight> {
58 59
        let mut txns = Vec::new();
        for txid_prefix in prefixes {
60 61 62 63 64 65 66
            let tx_rows: Vec<TxRow> = self.store
                .scan(&TxRow::filter(&txid_prefix))
                .iter()
                .map(|row| TxRow::from_row(row))
                .collect();
            for tx_row in tx_rows {
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
67
                let txn: Transaction = self.get_tx(&txid);
68 69
                txns.push(TxnHeight {
                    txn,
70
                    height: tx_row.height as i32,
71
                })
72 73 74 75 76
            }
        }
        txns
    }

Roman Zeyde's avatar
Roman Zeyde committed
77 78
    fn find_spending_input(&self, funding: &FundingOutput) -> Option<SpendingInput> {
        let spending_txns: Vec<TxnHeight> = self.load_txns(
79
            self.store
80
                .scan(&TxInRow::filter(&funding.txn_id, funding.output_index))
81
                .iter()
82
                .map(|row| TxInRow::from_row(row).txid_prefix)
83 84
                .collect(),
        );
Roman Zeyde's avatar
Roman Zeyde committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
        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))
102 103 104 105 106
        } else {
            None
        }
    }

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    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
123 124 125 126 127 128 129 130
    pub fn status(&self, script_hash: &[u8]) -> Status {
        let mut status = Status {
            balance: 0,
            funding: vec![],
            spending: vec![],
        };

        let funding_txns = self.load_txns(
131
            self.store
132
                .scan(&TxOutRow::filter(script_hash))
133
                .iter()
134
                .map(|row| TxOutRow::from_row(row).txid_prefix)
135 136
                .collect(),
        );
Roman Zeyde's avatar
Roman Zeyde committed
137
        for t in funding_txns {
138 139 140
            status
                .funding
                .extend(self.find_funding_outputs(&t, script_hash));
141
        }
Roman Zeyde's avatar
Roman Zeyde committed
142 143 144 145 146 147 148 149
        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
150
    }
151

152
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Transaction {
153
        self.daemon
154 155
            .gettransaction(tx_hash)
            .expect(&format!("failed to load tx {}", tx_hash))
156
    }
157

Roman Zeyde's avatar
Roman Zeyde committed
158
    pub fn get_headers(&self, heights: &[usize]) -> Vec<BlockHeader> {
159 160 161
        let headers_list = self.index.headers_list();
        let headers = headers_list.headers();
        let mut result = Vec::new();
Roman Zeyde's avatar
Roman Zeyde committed
162 163 164 165 166
        for height in heights {
            let header: &BlockHeader = match headers.get(*height) {
                Some(header) => header.header(),
                None => break,
            };
Roman Zeyde's avatar
Roman Zeyde committed
167
            result.push(*header);
168 169 170
        }
        result
    }
Roman Zeyde's avatar
Roman Zeyde committed
171 172 173 174 175

    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
176 177 178 179 180 181 182 183 184

    // 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();
185
        let block: Block = self.daemon.getblock(&blockhash).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        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))
    }
205
}