rootstore.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. use darkfi_serial::{deserialize, serialize};
  2. use crate::{crypto::merkle_node::MerkleNode, Result};
  3. const SLED_ROOTS_TREE: &[u8] = b"_merkleroots";
  4. /// The `RootStore` is a `sled` tree storing all the Merkle roots seen
  5. /// in existing blocks. The key is the Merkle root itself, while the value
  6. /// is an empty vector that's not used.
  7. #[derive(Clone)]
  8. pub struct RootStore(sled::Tree);
  9. impl RootStore {
  10. /// Opens a new or existing `RootStore` on the given sled database.
  11. pub fn new(db: &sled::Db) -> Result<Self> {
  12. let tree = db.open_tree(SLED_ROOTS_TREE)?;
  13. Ok(Self(tree))
  14. }
  15. /// Insert a slice of [`MerkleNode`] into the store. With sled, the
  16. /// operation is done as a batch. The Merkle root is used as a key,
  17. /// while the value is an empty vector.
  18. pub fn insert(&self, roots: &[MerkleNode]) -> Result<()> {
  19. let mut batch = sled::Batch::default();
  20. for root in roots {
  21. batch.insert(serialize(root), vec![] as Vec<u8>);
  22. }
  23. self.0.apply_batch(batch)?;
  24. Ok(())
  25. }
  26. /// Check if the rootstore contains a given Merkle root.
  27. pub fn contains(&self, root: &MerkleNode) -> Result<bool> {
  28. Ok(self.0.contains_key(serialize(root))?)
  29. }
  30. /// Retrieve all Merkle roots from the store.
  31. /// Be careful as this will try to load everything in memory.
  32. pub fn get_all(&self) -> Result<Vec<MerkleNode>> {
  33. let mut roots = vec![];
  34. for root in self.0.iter() {
  35. let (key, _) = root.unwrap();
  36. let root = deserialize(&key)?;
  37. roots.push(root);
  38. }
  39. Ok(roots)
  40. }
  41. }