blockstore.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. use log::warn;
  2. use sled::Batch;
  3. use crate::{
  4. consensus2::{util::Timestamp, Block},
  5. util::serial::{deserialize, serialize},
  6. Error, Result,
  7. };
  8. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  9. const SLED_BLOCK_ORDER_TREE: &[u8] = b"_block_order";
  10. pub struct BlockStore(sled::Tree);
  11. impl BlockStore {
  12. /// Opens a new or existing `BlockStore` on the given sled database.
  13. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  14. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  15. let store = Self(tree);
  16. // In case the store is empty, create the genesis block.
  17. if store.0.is_empty() {
  18. store.insert(&[Block::genesis_block(genesis_ts, genesis_data)])?;
  19. }
  20. Ok(store)
  21. }
  22. /// Insert a slice of [`Block`] into the blockstore. With sled, the
  23. /// operation is done as a batch.
  24. /// The blocks are hashed with BLAKE3 and this blockhash is used as
  25. /// the key, while value is the serialized block itself.
  26. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  27. let mut ret = Vec::with_capacity(blocks.len());
  28. let mut batch = Batch::default();
  29. for i in blocks {
  30. let serialized = serialize(i);
  31. let blockhash = blake3::hash(&serialized);
  32. batch.insert(blockhash.as_bytes(), serialized);
  33. ret.push(blockhash);
  34. }
  35. self.0.apply_batch(batch)?;
  36. Ok(ret)
  37. }
  38. /// Fetch given blockhashes from the blockstore.
  39. /// The resulting vector contains `Option` which is `Some` if the block
  40. /// was found in the blockstore, and `None`, if it has not.
  41. pub fn get(&self, blockhashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  42. let mut ret = Vec::with_capacity(blockhashes.len());
  43. for i in blockhashes {
  44. if let Some(found) = self.0.get(i.as_bytes())? {
  45. let block = deserialize(&found)?;
  46. ret.push(Some(block));
  47. } else {
  48. if strict {
  49. let s = i.to_hex().as_str().to_string();
  50. return Err(Error::BlockNotFound(s))
  51. }
  52. ret.push(None);
  53. }
  54. }
  55. Ok(ret)
  56. }
  57. /// Check if the blockstore contains a given blockhash.
  58. pub fn contains(&self, blockhash: blake3::Hash) -> Result<bool> {
  59. Ok(self.0.contains_key(blockhash.as_bytes())?)
  60. }
  61. /// Retrieve all blocks.
  62. /// Be careful as this will try to load everything in memory.
  63. pub fn get_all(&self) -> Result<Vec<Option<(blake3::Hash, Block)>>> {
  64. let mut blocks = vec![];
  65. let iterator = self.0.into_iter().enumerate();
  66. for (_, r) in iterator {
  67. let (k, v) = r.unwrap();
  68. let hash_bytes: [u8; 32] = k.as_ref().try_into().unwrap();
  69. let block = deserialize(&v)?;
  70. blocks.push(Some((hash_bytes.into(), block)));
  71. }
  72. Ok(blocks)
  73. }
  74. }
  75. pub struct BlockOrderStore(sled::Tree);
  76. impl BlockOrderStore {
  77. /// Opens a new or existing `BlockOderStore` on the given sled database.
  78. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  79. let tree = db.open_tree(SLED_BLOCK_ORDER_TREE)?;
  80. let store = Self(tree);
  81. // In case the store is empty, create the genesis block.
  82. if store.0.is_empty() {
  83. let block = Block::genesis_block(genesis_ts, genesis_data);
  84. let blockhash = blake3::hash(&serialize(&block));
  85. store.insert(&[block.sl], &[blockhash])?;
  86. }
  87. Ok(store)
  88. }
  89. /// Insert a slice of slots and blockhashes into the store.
  90. /// The block slot is used as the key, and the hash as value.
  91. pub fn insert(&self, slots: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  92. assert_eq!(slots.len(), hashes.len());
  93. let mut batch = Batch::default();
  94. for (i, sl) in slots.iter().enumerate() {
  95. batch.insert(&sl.to_be_bytes(), hashes[i].as_bytes());
  96. }
  97. self.0.apply_batch(batch)?;
  98. Ok(())
  99. }
  100. /// Retrieve all hashes given slots.
  101. pub fn get(&self, slots: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  102. //let mut ret = Vec::with_capacity(slots.len());
  103. let mut ret = vec![];
  104. for i in slots {
  105. if let Some(found) = self.0.get(i.to_be_bytes())? {
  106. let hash_bytes: [u8; 32] = found.as_ref().try_into().unwrap();
  107. let hash = blake3::Hash::from(hash_bytes);
  108. ret.push(Some(hash));
  109. } else {
  110. if strict {
  111. warn!("BlockOrderStore::get() Slot {} not found", i);
  112. return Err(Error::SlotNotFound(*i))
  113. }
  114. ret.push(None);
  115. }
  116. }
  117. Ok(ret)
  118. }
  119. /// Retrieve the last block hash in the tree, based on the Ord
  120. /// implementation for Vec<u8>.
  121. pub fn get_last(&self) -> Result<Option<(u64, blake3::Hash)>> {
  122. if let Some(found) = self.0.last()? {
  123. let slot_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  124. let hash_bytes: [u8; 32] = found.1.as_ref().try_into().unwrap();
  125. let slot = u64::from_be_bytes(slot_bytes);
  126. let hash = blake3::Hash::from(hash_bytes);
  127. return Ok(Some((slot, hash)))
  128. }
  129. Ok(None)
  130. }
  131. /// Retrieve all block hashes.
  132. /// Be careful as this will try to load everything in memory.
  133. pub fn get_all(&self) -> Result<Vec<Option<(u64, blake3::Hash)>>> {
  134. let mut ret = vec![];
  135. let iterator = self.0.into_iter().enumerate();
  136. for (_, r) in iterator {
  137. let (k, v) = r.unwrap();
  138. let slot_bytes: [u8; 8] = k.as_ref().try_into().unwrap();
  139. let hash_bytes: [u8; 32] = v.as_ref().try_into().unwrap();
  140. let slot = u64::from_be_bytes(slot_bytes);
  141. let hash = blake3::Hash::from(hash_bytes);
  142. ret.push(Some((slot, hash)));
  143. }
  144. Ok(ret)
  145. }
  146. }