use anyhow::Result;
use bitcoin::{Transaction, Block, BlockHash, Txid};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use crate::bitcoin::adapters::BitcoinStoragePort;
pub struct BitcoinStorageAdapter {
transactions: Arc<Mutex<HashMap<Txid, Transaction>>>,
blocks: Arc<Mutex<HashMap<BlockHash, Block>>>,
}
impl BitcoinStorageAdapter {
pub fn new() -> Self {
Self {
transactions: Arc::new(Mutex::new(HashMap::new())),
blocks: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn transaction_count(&self) -> usize {
self.transactions.lock().unwrap().len()
}
pub fn block_count(&self) -> usize {
self.blocks.lock().unwrap().len()
}
}
impl Default for BitcoinStorageAdapter {
fn default() -> Self {
Self::new()
}
}
impl BitcoinStoragePort for BitcoinStorageAdapter {
fn store_transaction(&self, tx: &Transaction) -> Result<()> {
let mut transactions = self.transactions.lock().unwrap();
transactions.insert(tx.txid(), tx.clone());
Ok(())
}
fn get_transaction(&self, txid: &Txid) -> Result<Option<Transaction>> {
let transactions = self.transactions.lock().unwrap();
Ok(transactions.get(txid).cloned())
}
fn store_block(&self, block: &Block) -> Result<()> {
let mut blocks = self.blocks.lock().unwrap();
blocks.insert(block.block_hash(), block.clone());
Ok(())
}
fn get_block(&self, hash: &BlockHash) -> Result<Option<Block>> {
let blocks = self.blocks.lock().unwrap();
Ok(blocks.get(hash).cloned())
}
}