use std::sync::Arc;
use kaspa_consensus_core::{utxo::utxo_diff::UtxoDiff, BlockHasher};
use kaspa_database::prelude::StoreError;
use kaspa_database::prelude::DB;
use kaspa_database::prelude::{BatchDbWriter, CachedDbAccess, DirectDbWriter};
use kaspa_hashes::Hash;
use rocksdb::WriteBatch;
pub trait UtxoDiffsStoreReader {
fn get(&self, hash: Hash) -> Result<Arc<UtxoDiff>, StoreError>;
}
pub trait UtxoDiffsStore: UtxoDiffsStoreReader {
fn insert(&self, hash: Hash, utxo_diff: Arc<UtxoDiff>) -> Result<(), StoreError>;
}
const STORE_PREFIX: &[u8] = b"utxo-diffs";
#[derive(Clone)]
pub struct DbUtxoDiffsStore {
db: Arc<DB>,
access: CachedDbAccess<Hash, Arc<UtxoDiff>, BlockHasher>,
}
impl DbUtxoDiffsStore {
pub fn new(db: Arc<DB>, cache_size: u64) -> Self {
Self { db: Arc::clone(&db), access: CachedDbAccess::new(Arc::clone(&db), cache_size, STORE_PREFIX.to_vec()) }
}
pub fn clone_with_new_cache(&self, cache_size: u64) -> Self {
Self::new(Arc::clone(&self.db), cache_size)
}
pub fn insert_batch(&self, batch: &mut WriteBatch, hash: Hash, utxo_diff: Arc<UtxoDiff>) -> Result<(), StoreError> {
if self.access.has(hash)? {
return Err(StoreError::KeyAlreadyExists(hash.to_string()));
}
self.access.write(BatchDbWriter::new(batch), hash, utxo_diff)?;
Ok(())
}
}
impl UtxoDiffsStoreReader for DbUtxoDiffsStore {
fn get(&self, hash: Hash) -> Result<Arc<UtxoDiff>, StoreError> {
self.access.read(hash)
}
}
impl UtxoDiffsStore for DbUtxoDiffsStore {
fn insert(&self, hash: Hash, utxo_diff: Arc<UtxoDiff>) -> Result<(), StoreError> {
if self.access.has(hash)? {
return Err(StoreError::KeyAlreadyExists(hash.to_string()));
}
self.access.write(DirectDbWriter::new(&self.db), hash, utxo_diff)?;
Ok(())
}
}