Skip to content

Commit

Permalink
Add a simple kv database for cfilters
Browse files Browse the repository at this point in the history
Use a kv bucket to store all filters on disk
  • Loading branch information
Davidson-Souza committed Dec 1, 2023
1 parent 13dd150 commit 6533075
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
55 changes: 55 additions & 0 deletions crates/floresta-compact-filters/src/kv_filter_database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use std::path::PathBuf;

use bitcoin::util::bip158::BlockFilter;
use kv::{Bucket, Integer, Config};

use crate::BlockFilterStore;

/// Stores the block filters insinde a kv database
pub struct KvFilterStore<'a> {
bucket: Bucket<'a, Integer, Vec<u8>>,
}

impl KvFilterStore<'_> {
/// Creates a new [KvFilterStore] that stores it's content in `datadir`.
///
/// If the path does't exist it'll be created. This store uses compression by default, if you
/// want to make more granular configuration over the underlying Kv database, use `with_config`
/// instead.
pub fn new(datadir: &PathBuf) -> Self {
let store = kv::Store::new(kv::Config {
path: datadir.to_owned(),
temporary: false,
use_compression: true,
flush_every_ms: None,
cache_capacity: None,
segment_size: None,
}).expect("Could not open store");

let bucket = store.bucket(Some("cfilters")).unwrap();
KvFilterStore { bucket }

}
/// Creates a new [KvFilterStore] that stores it's content with a given config
pub fn with_config(config: Config) -> Self {
let store = kv::Store::new(config).expect("Could not open database");
let bucket = store.bucket(Some("cffilters")).unwrap();
KvFilterStore { bucket }
}
}

impl BlockFilterStore for KvFilterStore<'_> {
fn get_filter(&self, block_height: u64) -> Option<bitcoin::util::bip158::BlockFilter> {
let value = self
.bucket
.get(&Integer::from(block_height))
.ok()
.flatten()?;
Some(BlockFilter::new(&value))
}
fn put_filter(&self, block_height: u64, block_filter: bitcoin::util::bip158::BlockFilter) {
self.bucket
.set(&Integer::from(block_height), &block_filter.content)
.expect("Bucket should be open");
}
}
2 changes: 1 addition & 1 deletion crates/floresta-compact-filters/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl BlockFilterBackend {
ser_input[0..32].clone_from_slice(&input.previous_output.txid);
ser_input[32..].clone_from_slice(&input.previous_output.vout.to_be_bytes());
filter.put(&ser_input);
});
})
}
}
fn write_tx_outs(&self, tx: &Transaction, filter: &mut FilterBuilder) {
Expand Down

0 comments on commit 6533075

Please sign in to comment.