clementine_core/builder/
block_cache.rs1use bitcoin::{Block, OutPoint, Transaction, Txid, Witness};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone)]
6pub struct BlockCache {
7 pub(crate) txids: HashMap<Txid, usize>,
8 pub(crate) spent_utxos: HashMap<OutPoint, usize>,
9 pub(crate) block_height: u32,
10 pub(crate) block: Block,
11}
12
13impl BlockCache {
14 pub fn from_block(block: Block, block_height: u32) -> Self {
15 let mut txids = HashMap::new();
16 let mut spent_utxos = HashMap::new();
17 for (idx, tx) in block.txdata.iter().enumerate() {
18 txids.insert(tx.compute_txid(), idx);
19
20 for input in &tx.input {
22 spent_utxos.insert(input.previous_output, idx);
23 }
24 }
25
26 Self {
27 txids,
28 spent_utxos,
29 block_height,
30 block,
31 }
32 }
33
34 pub fn get_tx_with_index(&self, idx: usize) -> Option<&Transaction> {
35 self.block.txdata.get(idx)
36 }
37
38 pub fn get_tx_of_utxo(&self, utxo: &OutPoint) -> Option<&Transaction> {
39 self.spent_utxos
40 .get(utxo)
41 .and_then(|idx| self.get_tx_with_index(*idx))
42 }
43
44 pub fn get_txid_of_utxo(&self, utxo: &OutPoint) -> Option<Txid> {
45 self.get_tx_of_utxo(utxo).map(|tx| tx.compute_txid())
46 }
47
48 pub fn get_witness_of_utxo(&self, utxo: &OutPoint) -> Option<Witness> {
49 self.get_tx_of_utxo(utxo).and_then(|tx| {
50 tx.input
51 .iter()
52 .find(|input| input.previous_output == *utxo)
53 .map(|input| input.witness.clone())
54 })
55 }
56
57 pub fn contains_txid(&self, txid: &Txid) -> bool {
58 self.txids.contains_key(txid)
59 }
60
61 pub fn is_utxo_spent(&self, outpoint: &OutPoint) -> bool {
62 self.spent_utxos.contains_key(outpoint)
63 }
64}