blockstore.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. use crate::{
  2. consensus::{Block, Header},
  3. util::{
  4. serial::{deserialize, serialize},
  5. time::Timestamp,
  6. },
  7. Error, Result,
  8. };
  9. const SLED_HEADER_TREE: &[u8] = b"_headers";
  10. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  11. const SLED_BLOCK_ORDER_TREE: &[u8] = b"_block_order";
  12. /// The `HeaderStore` is a `sled` tree storing all the blockchain's blocks' headers
  13. /// where the key is the headers's hash, and value is the serialized header.
  14. #[derive(Clone)]
  15. pub struct HeaderStore(sled::Tree);
  16. impl HeaderStore {
  17. /// Opens a new or existing `HeaderStore` on the given sled database.
  18. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  19. let tree = db.open_tree(SLED_HEADER_TREE)?;
  20. let store = Self(tree);
  21. // In case the store is empty, initialize it with the genesis header.
  22. if store.0.is_empty() {
  23. let genesis_header = Header::genesis_header(genesis_ts, genesis_data);
  24. store.insert(&[genesis_header])?;
  25. }
  26. Ok(store)
  27. }
  28. /// Insert a slice of [`Header`] into the blockstore. With sled, the
  29. /// operation is done as a batch.
  30. /// The headers are hashed with BLAKE3 and this headerhash is used as
  31. /// the key, while value is the serialized [`Header`] itself.
  32. /// On success, the function returns the header hashes in the same order.
  33. pub fn insert(&self, headers: &[Header]) -> Result<Vec<blake3::Hash>> {
  34. let mut ret = Vec::with_capacity(headers.len());
  35. let mut batch = sled::Batch::default();
  36. for header in headers {
  37. let serialized = serialize(header);
  38. let headerhash = blake3::hash(&serialized);
  39. batch.insert(headerhash.as_bytes(), serialized);
  40. ret.push(headerhash);
  41. }
  42. self.0.apply_batch(batch)?;
  43. Ok(ret)
  44. }
  45. /// Check if the headerstore contains a given headerhash.
  46. pub fn contains(&self, headerhash: &blake3::Hash) -> Result<bool> {
  47. Ok(self.0.contains_key(headerhash.as_bytes())?)
  48. }
  49. /// Fetch given headerhashes from the headerstore.
  50. /// The resulting vector contains `Option`, which is `Some` if the header
  51. /// was found in the headerstore, and otherwise it is `None`, if it has not.
  52. /// The second parameter is a boolean which tells the function to fail in
  53. /// case at least one header was not found.
  54. pub fn get(&self, headerhashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Header>>> {
  55. let mut ret = Vec::with_capacity(headerhashes.len());
  56. for hash in headerhashes {
  57. if let Some(found) = self.0.get(hash.as_bytes())? {
  58. let header = deserialize(&found)?;
  59. ret.push(Some(header));
  60. } else {
  61. if strict {
  62. let s = hash.to_hex().as_str().to_string();
  63. return Err(Error::HeaderNotFound(s))
  64. }
  65. ret.push(None);
  66. }
  67. }
  68. Ok(ret)
  69. }
  70. /// Retrieve all headers from the headerstore in the form of a tuple
  71. /// (`headerhash`, `header`).
  72. /// Be careful as this will try to load everything in memory.
  73. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Header)>> {
  74. let mut headers = vec![];
  75. for header in self.0.iter() {
  76. let (key, value) = header.unwrap();
  77. let hash_bytes: [u8; 32] = key.as_ref().try_into().unwrap();
  78. let header = deserialize(&value)?;
  79. headers.push((hash_bytes.into(), header));
  80. }
  81. Ok(headers)
  82. }
  83. }
  84. /// The `BlockStore` is a `sled` tree storing all the blockchain's blocks
  85. /// where the key is the block's headers' hash, and value is the serialized block.
  86. #[derive(Clone)]
  87. pub struct BlockStore(sled::Tree);
  88. impl BlockStore {
  89. /// Opens a new or existing `BlockStore` on the given sled database.
  90. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  91. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  92. let store = Self(tree);
  93. // In case the store is empty, initialize it with the genesis block.
  94. if store.0.is_empty() {
  95. let genesis_block = Block::genesis_block(genesis_ts, genesis_data);
  96. store.insert(&[genesis_block])?;
  97. }
  98. Ok(store)
  99. }
  100. /// Insert a slice of [`Block`] into the store. With sled, the
  101. /// operation is done as a batch.
  102. /// The block's header is used as the key, while value is the serialized [`Block`] itself.
  103. pub fn insert(&self, blocks: &[Block]) -> Result<()> {
  104. let mut batch = sled::Batch::default();
  105. for block in blocks {
  106. batch.insert(block.header.as_bytes(), serialize(block));
  107. }
  108. self.0.apply_batch(batch)?;
  109. Ok(())
  110. }
  111. /// Check if the blockstore contains a given headerhash.
  112. pub fn contains(&self, headerhash: &blake3::Hash) -> Result<bool> {
  113. Ok(self.0.contains_key(headerhash.as_bytes())?)
  114. }
  115. /// Fetch given headerhashes from the blockstore.
  116. /// The resulting vector contains `Option`, which is `Some` if the block
  117. /// was found in the blockstore, and otherwise it is `None`, if it has not.
  118. /// The second parameter is a boolean which tells the function to fail in
  119. /// case at least one block was not found.
  120. pub fn get(&self, headerhashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  121. let mut ret = Vec::with_capacity(headerhashes.len());
  122. for hash in headerhashes {
  123. if let Some(found) = self.0.get(hash.as_bytes())? {
  124. let block = deserialize(&found)?;
  125. ret.push(Some(block));
  126. } else {
  127. if strict {
  128. let s = hash.to_hex().as_str().to_string();
  129. return Err(Error::BlockNotFound(s))
  130. }
  131. ret.push(None);
  132. }
  133. }
  134. Ok(ret)
  135. }
  136. /// Retrieve all blocks from the blockstore in the form of a tuple
  137. /// (`headerhash`, `block`).
  138. /// Be careful as this will try to load everything in memory.
  139. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Block)>> {
  140. let mut blocks = vec![];
  141. for block in self.0.iter() {
  142. let (key, value) = block.unwrap();
  143. let hash_bytes: [u8; 32] = key.as_ref().try_into().unwrap();
  144. let block = deserialize(&value)?;
  145. blocks.push((hash_bytes.into(), block));
  146. }
  147. Ok(blocks)
  148. }
  149. }
  150. /// The `BlockOrderStore` is a `sled` tree storing the order of the
  151. /// blockchain's slots, where the key is the slot uid, and the value is
  152. /// the block's headers' hash. [`BlockStore`] can be queried with this hash.
  153. pub struct BlockOrderStore(sled::Tree);
  154. impl BlockOrderStore {
  155. /// Opens a new or existing `BlockOrderStore` on the given sled database.
  156. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  157. let tree = db.open_tree(SLED_BLOCK_ORDER_TREE)?;
  158. let store = Self(tree);
  159. // In case the store is empty, initialize it with the genesis block.
  160. if store.0.is_empty() {
  161. let genesis_block = Block::genesis_block(genesis_ts, genesis_data);
  162. store.insert(&[0], &[genesis_block.header])?;
  163. }
  164. Ok(store)
  165. }
  166. /// Insert a slice of slots and headerhashes into the store. With sled, the
  167. /// operation is done as a batch.
  168. /// The block slot is used as the key, and the headerhash is used as value.
  169. pub fn insert(&self, slots: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  170. assert_eq!(slots.len(), hashes.len());
  171. let mut batch = sled::Batch::default();
  172. for (i, sl) in slots.iter().enumerate() {
  173. batch.insert(&sl.to_be_bytes(), hashes[i].as_bytes());
  174. }
  175. self.0.apply_batch(batch)?;
  176. Ok(())
  177. }
  178. /// Check if the blockorderstore contains a given slot.
  179. pub fn contains(&self, slot: u64) -> Result<bool> {
  180. Ok(self.0.contains_key(slot.to_be_bytes())?)
  181. }
  182. /// Fetch given slots from the blockorderstore.
  183. /// The resulting vector contains `Option`, which is `Some` if the slot
  184. /// was found in the blockstore, and otherwise it is `None`, if it has not.
  185. /// The second parameter is a boolean which tells the function to fail in
  186. /// case at least one slot was not found.
  187. pub fn get(&self, slots: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  188. let mut ret = Vec::with_capacity(slots.len());
  189. for slot in slots {
  190. if let Some(found) = self.0.get(slot.to_be_bytes())? {
  191. let hash_bytes: [u8; 32] = found.as_ref().try_into().unwrap();
  192. let hash = blake3::Hash::from(hash_bytes);
  193. ret.push(Some(hash));
  194. } else {
  195. if strict {
  196. return Err(Error::SlotNotFound(*slot))
  197. }
  198. ret.push(None);
  199. }
  200. }
  201. Ok(ret)
  202. }
  203. /// Retrieve all slots from the blockorderstore in the form of a tuple
  204. /// (`slot`, `headerhash`).
  205. /// Be careful as this will try to load everything in memory.
  206. pub fn get_all(&self) -> Result<Vec<(u64, blake3::Hash)>> {
  207. let mut slots = vec![];
  208. for slot in self.0.iter() {
  209. let (key, value) = slot.unwrap();
  210. let slot_bytes: [u8; 8] = key.as_ref().try_into().unwrap();
  211. let hash_bytes: [u8; 32] = value.as_ref().try_into().unwrap();
  212. let slot = u64::from_be_bytes(slot_bytes);
  213. let hash = blake3::Hash::from(hash_bytes);
  214. slots.push((slot, hash));
  215. }
  216. Ok(slots)
  217. }
  218. /// Fetch n hashes after given slot. In the iteration, if a slot is not
  219. /// found, the iteration stops and the function returns what it has found
  220. /// so far in the `BlockOrderStore`.
  221. pub fn get_after(&self, slot: u64, n: u64) -> Result<Vec<blake3::Hash>> {
  222. let mut ret = vec![];
  223. let mut key = slot;
  224. let mut counter = 0;
  225. while counter <= n {
  226. if let Some(found) = self.0.get_gt(key.to_be_bytes())? {
  227. let key_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  228. key = u64::from_be_bytes(key_bytes);
  229. let header_hash = deserialize(&found.1)?;
  230. ret.push(header_hash);
  231. counter += 1;
  232. continue
  233. }
  234. break
  235. }
  236. Ok(ret)
  237. }
  238. /// Fetch the last block headerhash in the tree, based on the `Ord`
  239. /// implementation for `Vec<u8>`. This should not be able to
  240. /// fail because we initialize the store with the genesis block.
  241. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  242. let found = self.0.last()?.unwrap();
  243. let slot_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  244. let hash_bytes: [u8; 32] = found.1.as_ref().try_into().unwrap();
  245. let slot = u64::from_be_bytes(slot_bytes);
  246. let hash = blake3::Hash::from(hash_bytes);
  247. Ok((slot, hash))
  248. }
  249. }