block_store.rs 12 KB

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