query.rs 15.6 KB
Newer Older
1
use bitcoin::blockdata::transaction::Transaction;
2
use bitcoin::consensus::encode::deserialize;
Roman Zeyde's avatar
Roman Zeyde committed
3 4 5
use bitcoin_hashes::hex::ToHex;
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
use bitcoin_hashes::Hash;
6 7
use crypto::digest::Digest;
use crypto::sha2::Sha256;
Roman Zeyde's avatar
Roman Zeyde committed
8
use serde_json::Value;
9
use std::collections::HashMap;
10
use std::sync::{Arc, RwLock};
11

Roman Zeyde's avatar
Roman Zeyde committed
12
use crate::app::App;
13
use crate::cache::TransactionCache;
Roman Zeyde's avatar
Roman Zeyde committed
14 15 16 17 18 19
use crate::errors::*;
use crate::index::{compute_script_hash, TxInRow, TxOutRow, TxRow};
use crate::mempool::Tracker;
use crate::metrics::Metrics;
use crate::store::{ReadStore, Row};
use crate::util::{FullHash, HashPrefix, HeaderEntry};
Roman Zeyde's avatar
Roman Zeyde committed
20

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

28 29
type OutPoint = (Sha256dHash, usize); // (txid, output_index)

30 31
struct SpendingInput {
    txn_id: Sha256dHash,
32
    height: u32,
33
    funding_output: OutPoint,
34
    value: u64,
Roman Zeyde's avatar
Roman Zeyde committed
35 36 37
}

pub struct Status {
38 39 40 41
    confirmed: (Vec<FundingOutput>, Vec<SpendingInput>),
    mempool: (Vec<FundingOutput>, Vec<SpendingInput>),
}

42 43 44 45
fn calc_balance((funding, spending): &(Vec<FundingOutput>, Vec<SpendingInput>)) -> i64 {
    let funded: u64 = funding.iter().map(|output| output.value).sum();
    let spent: u64 = spending.iter().map(|input| input.value).sum();
    funded as i64 - spent as i64
Roman Zeyde's avatar
Roman Zeyde committed
46 47
}

48
impl Status {
49 50 51 52 53 54 55 56
    fn funding(&self) -> impl Iterator<Item = &FundingOutput> {
        self.confirmed.0.iter().chain(self.mempool.0.iter())
    }

    fn spending(&self) -> impl Iterator<Item = &SpendingInput> {
        self.confirmed.1.iter().chain(self.mempool.1.iter())
    }

57
    pub fn confirmed_balance(&self) -> i64 {
58 59 60
        calc_balance(&self.confirmed)
    }

61
    pub fn mempool_balance(&self) -> i64 {
62
        calc_balance(&self.mempool)
63 64
    }

65 66
    pub fn history(&self) -> Vec<(i32, Sha256dHash)> {
        let mut txns_map = HashMap::<Sha256dHash, i32>::new();
67
        for f in self.funding() {
68
            txns_map.insert(f.txn_id, f.height as i32);
69
        }
70
        for s in self.spending() {
71
            txns_map.insert(s.txn_id, s.height as i32);
72 73 74
        }
        let mut txns: Vec<(i32, Sha256dHash)> =
            txns_map.into_iter().map(|item| (item.1, item.0)).collect();
75
        txns.sort_unstable();
76 77 78
        txns
    }

79 80 81 82 83 84
    pub fn unspent(&self) -> Vec<&FundingOutput> {
        let mut outputs_map = HashMap::<OutPoint, &FundingOutput>::new();
        for f in self.funding() {
            outputs_map.insert((f.txn_id, f.output_index), f);
        }
        for s in self.spending() {
Roman Zeyde's avatar
Roman Zeyde committed
85
            if outputs_map.remove(&s.funding_output).is_none() {
86 87 88
                warn!("failed to remove {:?}", s.funding_output);
            }
        }
89
        let mut outputs = outputs_map
90 91
            .into_iter()
            .map(|item| item.1) // a reference to unspent output
92 93 94
            .collect::<Vec<&FundingOutput>>();
        outputs.sort_unstable_by_key(|out| out.height);
        outputs
95 96
    }

97 98 99 100 101 102 103 104
    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 {
Roman Zeyde's avatar
Roman Zeyde committed
105
                let part = format!("{}:{}:", txn_id.to_hex(), height);
106 107 108 109 110 111 112 113
                sha2.input(part.as_bytes());
            }
            sha2.result(&mut hash);
            Some(hash)
        }
    }
}

Roman Zeyde's avatar
Roman Zeyde committed
114 115
struct TxnHeight {
    txn: Transaction,
116
    height: u32,
Roman Zeyde's avatar
Roman Zeyde committed
117 118
}

Roman Zeyde's avatar
Roman Zeyde committed
119 120
fn merklize(left: Sha256dHash, right: Sha256dHash) -> Sha256dHash {
    let data = [&left[..], &right[..]].concat();
Roman Zeyde's avatar
Roman Zeyde committed
121
    Sha256dHash::hash(&data)
Roman Zeyde's avatar
Roman Zeyde committed
122 123
}

124 125 126 127 128 129 130
fn create_merkle_branch_and_root(
    mut hashes: Vec<Sha256dHash>,
    mut index: usize,
) -> (Vec<Sha256dHash>, Sha256dHash) {
    let mut merkle = vec![];
    while hashes.len() > 1 {
        if hashes.len() % 2 != 0 {
Roman Zeyde's avatar
Roman Zeyde committed
131
            let last = *hashes.last().unwrap();
132 133 134 135
            hashes.push(last);
        }
        index = if index % 2 == 0 { index + 1 } else { index - 1 };
        merkle.push(hashes[index]);
Roman Zeyde's avatar
Roman Zeyde committed
136
        index /= 2;
137 138 139 140 141 142 143 144
        hashes = hashes
            .chunks(2)
            .map(|pair| merklize(pair[0], pair[1]))
            .collect()
    }
    (merkle, hashes[0])
}

145
// TODO: the functions below can be part of ReadStore.
146
fn txrow_by_txid(store: &dyn ReadStore, txid: &Sha256dHash) -> Option<TxRow> {
147 148 149 150 151
    let key = TxRow::filter_full(&txid);
    let value = store.get(&key)?;
    Some(TxRow::from_row(&Row { key, value }))
}

152
fn txrows_by_prefix(store: &dyn ReadStore, txid_prefix: HashPrefix) -> Vec<TxRow> {
153
    store
Roman Zeyde's avatar
Roman Zeyde committed
154
        .scan(&TxRow::filter_prefix(txid_prefix))
155 156 157 158
        .iter()
        .map(|row| TxRow::from_row(row))
        .collect()
}
159

160
fn txids_by_script_hash(store: &dyn ReadStore, script_hash: &[u8]) -> Vec<HashPrefix> {
161 162 163 164 165 166
    store
        .scan(&TxOutRow::filter(script_hash))
        .iter()
        .map(|row| TxOutRow::from_row(row).txid_prefix)
        .collect()
}
167

168
fn txids_by_funding_output(
169
    store: &dyn ReadStore,
170 171 172 173 174 175 176 177
    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()
178 179
}

180 181
pub struct Query {
    app: Arc<App>,
182
    tracker: RwLock<Tracker>,
183
    tx_cache: TransactionCache,
184
    txid_limit: usize,
185 186
}

187
impl Query {
188 189 190 191 192 193
    pub fn new(
        app: Arc<App>,
        metrics: &Metrics,
        tx_cache: TransactionCache,
        txid_limit: usize,
    ) -> Arc<Query> {
194
        Arc::new(Query {
195
            app,
196
            tracker: RwLock::new(Tracker::new(metrics)),
197
            tx_cache,
198
            txid_limit,
199
        })
200 201
    }

202 203
    fn load_txns_by_prefix(
        &self,
204
        store: &dyn ReadStore,
205 206
        prefixes: Vec<HashPrefix>,
    ) -> Result<Vec<TxnHeight>> {
Roman Zeyde's avatar
Roman Zeyde committed
207
        let mut txns = vec![];
208
        for txid_prefix in prefixes {
Roman Zeyde's avatar
Roman Zeyde committed
209
            for tx_row in txrows_by_prefix(store, txid_prefix) {
210
                let txid: Sha256dHash = deserialize(&tx_row.key.txid).unwrap();
211
                let txn = self.load_txn(&txid, Some(tx_row.height))?;
212 213
                txns.push(TxnHeight {
                    txn,
214
                    height: tx_row.height,
215
                })
216 217
            }
        }
218
        Ok(txns)
219 220
    }

221 222
    fn find_spending_input(
        &self,
223
        store: &dyn ReadStore,
224
        funding: &FundingOutput,
225
    ) -> Result<Option<SpendingInput>> {
226
        let spending_txns: Vec<TxnHeight> = self.load_txns_by_prefix(
227
            store,
228
            txids_by_funding_output(store, &funding.txn_id, funding.output_index),
229
        )?;
Roman Zeyde's avatar
Roman Zeyde committed
230
        let mut spending_inputs = vec![];
Roman Zeyde's avatar
Roman Zeyde committed
231
        for t in &spending_txns {
232
            for input in t.txn.input.iter() {
233 234
                if input.previous_output.txid == funding.txn_id
                    && input.previous_output.vout == funding.output_index as u32
Roman Zeyde's avatar
Roman Zeyde committed
235 236 237 238
                {
                    spending_inputs.push(SpendingInput {
                        txn_id: t.txn.txid(),
                        height: t.height,
239
                        funding_output: (funding.txn_id, funding.output_index),
240
                        value: funding.value,
Roman Zeyde's avatar
Roman Zeyde committed
241 242 243 244 245
                    })
                }
            }
        }
        assert!(spending_inputs.len() <= 1);
246
        Ok(if spending_inputs.len() == 1 {
Roman Zeyde's avatar
Roman Zeyde committed
247
            Some(spending_inputs.remove(0))
248 249
        } else {
            None
250
        })
251 252
    }

253
    fn find_funding_outputs(&self, t: &TxnHeight, script_hash: &[u8]) -> Vec<FundingOutput> {
Roman Zeyde's avatar
Roman Zeyde committed
254
        let mut result = vec![];
255
        let txn_id = t.txn.txid();
Roman Zeyde's avatar
Roman Zeyde committed
256
        for (index, output) in t.txn.output.iter().enumerate() {
257 258
            if compute_script_hash(&output.script_pubkey[..]) == script_hash {
                result.push(FundingOutput {
Roman Zeyde's avatar
Roman Zeyde committed
259
                    txn_id,
260 261 262 263 264 265 266 267 268
                    height: t.height,
                    output_index: index,
                    value: output.value,
                })
            }
        }
        result
    }

269 270 271 272
    fn confirmed_status(
        &self,
        script_hash: &[u8],
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
273 274
        let mut funding = vec![];
        let mut spending = vec![];
275 276
        let read_store = self.app.read_store();
        let txid_prefixes = txids_by_script_hash(read_store, script_hash);
277
        // if the limit is enabled
Roman Zeyde's avatar
Roman Zeyde committed
278 279 280 281 282
        if self.txid_limit > 0 && txid_prefixes.len() > self.txid_limit {
            bail!(
                "{}+ transactions found, query may take a long time",
                txid_prefixes.len()
            );
283
        }
284
        for t in self.load_txns_by_prefix(read_store, txid_prefixes)? {
285
            funding.extend(self.find_funding_outputs(&t, script_hash));
286
        }
287
        for funding_output in &funding {
288
            if let Some(spent) = self.find_spending_input(read_store, &funding_output)? {
289
                spending.push(spent);
290 291
            }
        }
292
        Ok((funding, spending))
293 294
    }

295 296 297 298
    fn mempool_status(
        &self,
        script_hash: &[u8],
        confirmed_funding: &[FundingOutput],
299
    ) -> Result<(Vec<FundingOutput>, Vec<SpendingInput>)> {
300 301
        let mut funding = vec![];
        let mut spending = vec![];
302
        let tracker = self.tracker.read().unwrap();
303 304
        let txid_prefixes = txids_by_script_hash(tracker.index(), script_hash);
        for t in self.load_txns_by_prefix(tracker.index(), txid_prefixes)? {
305
            funding.extend(self.find_funding_outputs(&t, script_hash));
306
        }
307
        // // TODO: dedup outputs (somehow) both confirmed and in mempool (e.g. reorg?)
308
        for funding_output in funding.iter().chain(confirmed_funding.iter()) {
309
            if let Some(spent) = self.find_spending_input(tracker.index(), &funding_output)? {
310
                spending.push(spent);
Roman Zeyde's avatar
Roman Zeyde committed
311 312
            }
        }
313
        Ok((funding, spending))
314
    }
315

316
    pub fn status(&self, script_hash: &[u8]) -> Result<Status> {
Roman Zeyde's avatar
Roman Zeyde committed
317 318
        let confirmed = self
            .confirmed_status(script_hash)
319
            .chain_err(|| "failed to get confirmed status")?;
Roman Zeyde's avatar
Roman Zeyde committed
320 321
        let mempool = self
            .mempool_status(script_hash, &confirmed.0)
322
            .chain_err(|| "failed to get mempool status")?;
323
        Ok(Status { confirmed, mempool })
324 325
    }

326
    fn lookup_confirmed_blockhash(
327 328 329
        &self,
        tx_hash: &Sha256dHash,
        block_height: Option<u32>,
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    ) -> Result<Option<Sha256dHash>> {
        let blockhash = if self.tracker.read().unwrap().get_txn(&tx_hash).is_some() {
            None // found in mempool (as unconfirmed transaction)
        } else {
            // Lookup in confirmed transactions' index
            let height = match block_height {
                Some(height) => height,
                None => {
                    txrow_by_txid(self.app.read_store(), &tx_hash)
                        .chain_err(|| format!("not indexed tx {}", tx_hash))?
                        .height
                }
            };
            let header = self
                .app
                .index()
                .get_header(height as usize)
                .chain_err(|| format!("missing header at height {}", height))?;
            Some(*header.hash())
349
        };
350 351 352 353
        Ok(blockhash)
    }

    // Internal API for transaction retrieval
354 355 356
    fn load_txn(&self, txid: &Sha256dHash, block_height: Option<u32>) -> Result<Transaction> {
        self.tx_cache.get_or_else(&txid, || {
            let blockhash = self.lookup_confirmed_blockhash(txid, block_height)?;
357 358 359 360 361 362
            let value: Value = self
                .app
                .daemon()
                .gettransaction_raw(txid, blockhash, /*verbose*/ false)?;
            let value_hex: &str = value.as_str().chain_err(|| "non-string tx")?;
            hex::decode(&value_hex).chain_err(|| "non-hex tx")
363
        })
364 365 366 367 368 369 370 371
    }

    // Public API for transaction retrieval (for Electrum RPC)
    pub fn get_transaction(&self, tx_hash: &Sha256dHash, verbose: bool) -> Result<Value> {
        let blockhash = self.lookup_confirmed_blockhash(tx_hash, /*block_height*/ None)?;
        self.app
            .daemon()
            .gettransaction_raw(tx_hash, blockhash, verbose)
372
    }
373

374 375 376 377 378 379
    pub fn get_headers(&self, heights: &[usize]) -> Vec<HeaderEntry> {
        let index = self.app.index();
        heights
            .iter()
            .filter_map(|height| index.get_header(*height))
            .collect()
380
    }
Roman Zeyde's avatar
Roman Zeyde committed
381

382
    pub fn get_best_header(&self) -> Result<HeaderEntry> {
383
        let last_header = self.app.index().best_header();
384
        Ok(last_header.chain_err(|| "no headers indexed")?.clone())
Roman Zeyde's avatar
Roman Zeyde committed
385
    }
Roman Zeyde's avatar
Roman Zeyde committed
386 387 388 389 390

    pub fn get_merkle_proof(
        &self,
        tx_hash: &Sha256dHash,
        height: usize,
391
    ) -> Result<(Vec<Sha256dHash>, usize)> {
Roman Zeyde's avatar
Roman Zeyde committed
392 393
        let header_entry = self
            .app
394 395 396
            .index()
            .get_header(height)
            .chain_err(|| format!("missing block #{}", height))?;
397
        let txids = self.app.daemon().getblocktxids(&header_entry.hash())?;
398 399 400 401
        let pos = txids
            .iter()
            .position(|txid| txid == tx_hash)
            .chain_err(|| format!("missing txid {}", tx_hash))?;
402 403
        let (branch, _root) = create_merkle_branch_and_root(txids, pos);
        Ok((branch, pos))
Roman Zeyde's avatar
Roman Zeyde committed
404
    }
405

406 407 408 409 410 411
    pub fn get_header_merkle_proof(
        &self,
        height: usize,
        cp_height: usize,
    ) -> Result<(Vec<Sha256dHash>, Sha256dHash)> {
        if cp_height < height {
412
            bail!("cp_height #{} < height #{}", cp_height, height);
413 414 415 416
        }

        let best_height = self.get_best_header()?.height();
        if best_height < cp_height {
417
            bail!(
418
                "cp_height #{} above best block height #{}",
419 420 421
                cp_height,
                best_height
            );
422 423
        }

Roman Zeyde's avatar
Roman Zeyde committed
424
        let heights: Vec<usize> = (0..=cp_height).collect();
425 426
        let header_hashes: Vec<Sha256dHash> = self
            .get_headers(&heights)
427
            .into_iter()
428
            .map(|h| *h.hash())
429
            .collect();
430 431
        assert_eq!(header_hashes.len(), heights.len());
        Ok(create_merkle_branch_and_root(header_hashes, height))
432 433
    }

434 435 436 437 438 439 440 441 442 443 444 445
    pub fn get_id_from_pos(
        &self,
        height: usize,
        tx_pos: usize,
        want_merkle: bool,
    ) -> Result<(Sha256dHash, Vec<Sha256dHash>)> {
        let header_entry = self
            .app
            .index()
            .get_header(height)
            .chain_err(|| format!("missing block #{}", height))?;

446
        let txids = self.app.daemon().getblocktxids(header_entry.hash())?;
447 448 449 450
        let txid = *txids
            .get(tx_pos)
            .chain_err(|| format!("No tx in position #{} in block #{}", tx_pos, height))?;

451 452 453 454 455 456
        let branch = if want_merkle {
            create_merkle_branch_and_root(txids, tx_pos).0
        } else {
            vec![]
        };
        Ok((txid, branch))
457 458
    }

459
    pub fn broadcast(&self, txn: &Transaction) -> Result<Sha256dHash> {
460
        self.app.daemon().broadcast(txn)
461 462
    }

Roman Zeyde's avatar
Roman Zeyde committed
463
    pub fn update_mempool(&self) -> Result<()> {
Roman Zeyde's avatar
Roman Zeyde committed
464
        self.tracker.write().unwrap().update(self.app.daemon())
465
    }
466

467
    /// Returns [vsize, fee_rate] pairs (measured in vbytes and satoshis).
468
    pub fn get_fee_histogram(&self) -> Vec<(f32, u32)> {
469 470 471
        self.tracker.read().unwrap().fee_histogram().clone()
    }

472 473 474 475 476 477 478 479 480 481 482 483 484
    // Fee rate [BTC/kB] to be confirmed in `blocks` from now.
    pub fn estimate_fee(&self, blocks: usize) -> f32 {
        let mut total_vsize = 0u32;
        let mut last_fee_rate = 0.0;
        let blocks_in_vbytes = (blocks * 1_000_000) as u32; // assume ~1MB blocks
        for (fee_rate, vsize) in self.tracker.read().unwrap().fee_histogram() {
            last_fee_rate = *fee_rate;
            total_vsize += vsize;
            if total_vsize >= blocks_in_vbytes {
                break; // under-estimate the fee rate a bit
            }
        }
        last_fee_rate * 1e-5 // [BTC/kB] = 10^5 [sat/B]
485
    }
486 487 488 489

    pub fn get_banner(&self) -> Result<String> {
        self.app.get_banner()
    }
490
}