1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::sync::Arc;

use kaspa_database::prelude::DB;
use kaspa_database::prelude::{BatchDbWriter, CachedDbAccess, DirectDbWriter};
use kaspa_database::prelude::{StoreError, StoreResult};
use kaspa_hashes::Hash;
use rocksdb::WriteBatch;

use super::U64Key;

pub trait PastPruningPointsStoreReader {
    fn get(&self, index: u64) -> StoreResult<Hash>;
}

pub trait PastPruningPointsStore: PastPruningPointsStoreReader {
    // This is append only
    fn insert(&self, index: u64, pruning_point: Hash) -> StoreResult<()>;
    fn set(&self, index: u64, pruning_point: Hash) -> StoreResult<()>;
}

const STORE_PREFIX: &[u8] = b"past-pruning-points";

/// A DB + cache implementation of `PastPruningPointsStore` trait, with concurrency support.
#[derive(Clone)]
pub struct DbPastPruningPointsStore {
    db: Arc<DB>,
    access: CachedDbAccess<U64Key, Hash>,
}

impl DbPastPruningPointsStore {
    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, index: u64, pruning_point: Hash) -> Result<(), StoreError> {
        if self.access.has(index.into())? {
            return Err(StoreError::KeyAlreadyExists(index.to_string()));
        }
        self.access.write(BatchDbWriter::new(batch), index.into(), pruning_point)?;
        Ok(())
    }
}

impl PastPruningPointsStoreReader for DbPastPruningPointsStore {
    fn get(&self, index: u64) -> StoreResult<Hash> {
        self.access.read(index.into())
    }
}

impl PastPruningPointsStore for DbPastPruningPointsStore {
    fn insert(&self, index: u64, pruning_point: Hash) -> StoreResult<()> {
        if self.access.has(index.into())? {
            return Err(StoreError::KeyAlreadyExists(index.to_string()));
        }
        self.set(index, pruning_point)
    }

    fn set(&self, index: u64, pruning_point: Hash) -> StoreResult<()> {
        self.access.write(DirectDbWriter::new(&self.db), index.into(), pruning_point)?;
        Ok(())
    }
}