query.rs 9.55 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
struct FundingOutput {
    txn_id: Sha256dHash,
20
    height: u32,
21 22
    output_index: usize,
    value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
23 24
}

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

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

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

42 43 44
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
        for f in &self.funding {
45
            txns_map.insert(f.txn_id, f.height as i32);
46 47
        }
        for s in &self.spending {
48
            txns_map.insert(s.txn_id, s.height as i32);
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        }
        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
73 74
struct TxnHeight {
    txn: Transaction,
75
    height: u32,
Roman Zeyde's avatar
Roman Zeyde committed
76 77
}

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

83 84 85 86 87 88 89
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()
}
90

91 92 93 94 95 96 97
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()
}
98

99 100 101 102 103 104 105 106 107 108
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()
109 110
}

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

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

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

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

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

176 177 178
    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
179
        for (index, output) in t.txn.output.iter().enumerate() {
180 181 182 183 184 185 186 187 188 189 190 191
            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
    }

192
    fn confirmed_status(&self, script_hash: &[u8]) -> Status {
Roman Zeyde's avatar
Roman Zeyde committed
193 194 195 196 197
        let mut status = Status {
            balance: 0,
            funding: vec![],
            spending: vec![],
        };
198
        for t in self.load_txns(txids_by_script_hash(self.store, script_hash)) {
199 200 201
            status
                .funding
                .extend(self.find_funding_outputs(&t, script_hash));
202
        }
Roman Zeyde's avatar
Roman Zeyde committed
203
        for funding_output in &status.funding {
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
            if let Some(spent) = self.find_spending_input(self.store, &funding_output) {
                status.spending.push(spent);
            } else {
                status.balance += funding_output.value;
            }
        }
        status
    }

    fn mempool_status(&self, script_hash: &[u8], confirmed_status: &Status) -> Status {
        let mut status = Status {
            balance: 0,
            funding: vec![],
            spending: vec![],
        };
        let mempool_store = self.tracker.read().unwrap().build_index();
        for t in self.load_txns(txids_by_script_hash(&*mempool_store, script_hash)) {
            status
                .funding
                .extend(self.find_funding_outputs(&t, script_hash));
        }
        // TODO: dedup outputs (somehow) both confirmed and in mempool (e.g. reorg?)
        for funding_output in status.funding.iter().chain(confirmed_status.funding.iter()) {
            if let Some(spent) = self.find_spending_input(&*mempool_store, &funding_output) {
Roman Zeyde's avatar
Roman Zeyde committed
228 229 230 231 232
                status.spending.push(spent);
            } else {
                status.balance += funding_output.value;
            }
        }
Roman Zeyde's avatar
Roman Zeyde committed
233 234
        // TODO: update height to -1 for txns with any unconfirmed input
        // (https://electrumx.readthedocs.io/en/latest/protocol-basics.html#status)
Roman Zeyde's avatar
Roman Zeyde committed
235
        status
236
    }
237

238 239 240 241 242 243 244 245 246
    pub fn status(&self, script_hash: &[u8]) -> Status {
        let mut status = self.confirmed_status(script_hash);
        let mempool_status = self.mempool_status(script_hash, &status);
        status.balance += mempool_status.balance;
        status.funding.extend(mempool_status.funding);
        status.spending.extend(mempool_status.spending);
        status
    }

247
    pub fn get_tx(&self, tx_hash: &Sha256dHash) -> Transaction {
248
        self.daemon
249 250
            .gettransaction(tx_hash)
            .expect(&format!("failed to load tx {}", tx_hash))
251
    }
252

Roman Zeyde's avatar
Roman Zeyde committed
253
    pub fn get_headers(&self, heights: &[usize]) -> Vec<BlockHeader> {
254 255 256
        let headers_list = self.index.headers_list();
        let headers = headers_list.headers();
        let mut result = Vec::new();
Roman Zeyde's avatar
Roman Zeyde committed
257 258 259 260 261
        for height in heights {
            let header: &BlockHeader = match headers.get(*height) {
                Some(header) => header.header(),
                None => break,
            };
Roman Zeyde's avatar
Roman Zeyde committed
262
            result.push(*header);
263 264 265
        }
        result
    }
Roman Zeyde's avatar
Roman Zeyde committed
266 267 268 269 270

    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
271 272 273 274 275 276 277 278 279

    // 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();
280
        let block: Block = self.daemon.getblock(&blockhash).unwrap();
Roman Zeyde's avatar
Roman Zeyde committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        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))
    }
300

Roman Zeyde's avatar
Roman Zeyde committed
301
    pub fn update_mempool(&self) -> Result<()> {
302 303 304 305
        self.tracker
            .write()
            .unwrap()
            .update(self.daemon)
Roman Zeyde's avatar
Roman Zeyde committed
306
            .chain_err(|| "failed to update mempool")
307
    }
308 309 310 311

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