nfstore.rs 1.8 KB

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