nfstore.rs 1.8 KB

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