nfstore.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi_sdk::crypto::Nullifier;
  19. use darkfi_serial::{deserialize, serialize};
  20. use crate::Result;
  21. const SLED_NULLIFIER_TREE: &[u8] = b"_nullifiers";
  22. /// The `NullifierStore` is a `sled` tree storing all the nullifiers seen
  23. /// in existing blocks. The key is the nullifier itself, while the value
  24. /// is an empty vector that's not used. As a sidenote, perhaps we could
  25. /// hold the transaction hash where the nullifier was seen in the value.
  26. #[derive(Clone)]
  27. pub struct NullifierStore(sled::Tree);
  28. impl NullifierStore {
  29. /// Opens a new or existing `NullifierStore` on the given sled database.
  30. pub fn new(db: &sled::Db) -> Result<Self> {
  31. let tree = db.open_tree(SLED_NULLIFIER_TREE)?;
  32. Ok(Self(tree))
  33. }
  34. /// Insert a slice of [`Nullifier`] into the store. With sled, the
  35. /// operation is done as a batch. The nullifier is used as a key,
  36. /// while the value is an empty vector.
  37. pub fn insert(&self, nfs: &[Nullifier]) -> Result<()> {
  38. let mut batch = sled::Batch::default();
  39. for nf in nfs {
  40. batch.insert(serialize(nf), vec![] as Vec<u8>);
  41. }
  42. self.0.apply_batch(batch)?;
  43. Ok(())
  44. }
  45. /// Check if the nullifierstore contains a given nullifier.
  46. pub fn contains(&self, nullifier: &Nullifier) -> Result<bool> {
  47. Ok(self.0.contains_key(serialize(nullifier))?)
  48. }
  49. /// Retrieve all nullifiers from the store.
  50. /// Be careful as this will try to load everything in memory.
  51. pub fn get_all(&self) -> Result<Vec<Nullifier>> {
  52. let mut nullifiers = vec![];
  53. for nullifier in self.0.iter() {
  54. let (key, _) = nullifier.unwrap();
  55. let nullifier = deserialize(&key)?;
  56. nullifiers.push(nullifier);
  57. }
  58. Ok(nullifiers)
  59. }
  60. }