query.rs 6.58 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, HeaderEntry, Index, TxInRow, TxOutRow, TxRow};
10
use mempool::Tracker;
11
use store::Store;
12
use types::HashPrefix;
13

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

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

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

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

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

43 44 45 46 47 48 49
pub struct Query<'a> {
    store: &'a Store,
    daemon: &'a Daemon,
    index: &'a Index,
    tracker: RwLock<Tracker>,
}

50
// TODO: return errors instead of panics
51
impl<'a> Query<'a> {
52 53 54 55 56
    pub fn new(store: &'a Store, daemon: &'a Daemon, index: &'a Index) -> Query<'a> {
        Query {
            store,
            daemon,
            index,
57
            tracker: RwLock::new(Tracker::new()),
58
        }
59 60
    }

Roman Zeyde's avatar
Roman Zeyde committed
61
    fn load_txns(&self, prefixes: Vec<HashPrefix>) -> Vec<TxnHeight> {
62 63
        let mut txns = Vec::new();
        for txid_prefix in prefixes {
64 65 66 67 68 69 70
            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();
71
                let txn: Transaction = self.get_tx(&txid);
72 73
                txns.push(TxnHeight {
                    txn,
74
                    height: tx_row.height as i32,
75
                })
76 77 78 79 80
            }
        }
        txns
    }

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

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

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

156
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Transaction {
157
        self.daemon
158 159
            .gettransaction(tx_hash)
            .expect(&format!("failed to load tx {}", tx_hash))
160
    }
161

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

    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
180 181 182 183 184 185 186 187 188

    // 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();
189
        let block: Block = self.daemon.getblock(&blockhash).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        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))
    }
209 210 211 212 213 214 215 216

    pub fn update_mempool(&self) {
        self.tracker
            .write()
            .unwrap()
            .update(self.daemon)
            .expect("failed to update mempool")
    }
217
}