blockstore.rs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. use sled::Batch;
  2. use crate::{
  3. consensus2::{util::Timestamp, Block},
  4. util::serial::{deserialize, serialize},
  5. Result,
  6. };
  7. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  8. pub struct BlockStore(sled::Tree);
  9. impl BlockStore {
  10. /// Opens a new or existing `BlockStore` on the given sled database.
  11. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  12. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  13. let store = Self(tree);
  14. // In case the store is empty, create the genesis block.
  15. if store.0.is_empty() {
  16. store.insert(&[Block::genesis_block(genesis_ts, genesis_data)])?;
  17. }
  18. Ok(store)
  19. }
  20. /// Insert a slice of [`Block`] into the blockstore. With sled, the
  21. /// operation is done as a batch.
  22. /// The blocks are hashed with BLAKE3 and this blockhash is used as
  23. /// the key, while value is the serialized block itself.
  24. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  25. let mut ret = Vec::with_capacity(blocks.len());
  26. let mut batch = Batch::default();
  27. for i in blocks {
  28. let serialized = serialize(i);
  29. let blockhash = blake3::hash(&serialized);
  30. batch.insert(blockhash.as_bytes(), serialized);
  31. ret.push(blockhash);
  32. }
  33. self.0.apply_batch(batch)?;
  34. Ok(ret)
  35. }
  36. /// Fetch given blockhashes from the blockstore.
  37. /// The resulting vector contains `Option` which is `Some` if the block
  38. /// was found in the blockstore, and `None`, if it has not.
  39. pub fn get(&self, blockhashes: &[blake3::Hash]) -> Result<Vec<Option<Block>>> {
  40. let mut ret: Vec<Option<Block>> = Vec::with_capacity(blockhashes.len());
  41. for i in blockhashes {
  42. if let Some(found) = self.0.get(i.as_bytes())? {
  43. let block = deserialize(&found)?;
  44. ret.push(Some(block));
  45. } else {
  46. ret.push(None);
  47. }
  48. }
  49. Ok(ret)
  50. }
  51. /// Check if the blockstore contains a given blockhash.
  52. pub fn contains(&self, blockhash: blake3::Hash) -> Result<bool> {
  53. Ok(self.0.contains_key(blockhash.as_bytes())?)
  54. }
  55. /// Retrieve all blocks.
  56. /// Be careful as this will try to load everything in memory.
  57. pub fn get_all(&self) -> Result<Vec<Option<(blake3::Hash, Block)>>> {
  58. let mut blocks = vec![];
  59. let iterator = self.0.into_iter().enumerate();
  60. for (_, r) in iterator {
  61. let (k, v) = r.unwrap();
  62. let hash_bytes: [u8; 32] = k.as_ref().try_into().unwrap();
  63. let block = deserialize(&v)?;
  64. blocks.push(Some((hash_bytes.into(), block)));
  65. }
  66. Ok(blocks)
  67. }
  68. }