header_store.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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_sdk::{
  19. blockchain::block_version,
  20. crypto::MerkleTree,
  21. pasta::{group::ff::Field, pallas},
  22. };
  23. #[cfg(feature = "async-serial")]
  24. use darkfi_serial::async_trait;
  25. use darkfi_serial::{deserialize, serialize, Encodable, SerialDecodable, SerialEncodable};
  26. use crate::{util::time::Timestamp, Error, Result};
  27. use super::{parse_record, SledDbOverlayPtr};
  28. /// This struct represents a tuple of the form (version, previous, epoch, height, timestamp, nonce, merkle_root).
  29. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  30. pub struct Header {
  31. /// Block version
  32. pub version: u8,
  33. /// Previous block hash
  34. pub previous: blake3::Hash,
  35. /// Epoch number
  36. pub epoch: u64,
  37. /// Block/Slot height
  38. pub height: u64,
  39. /// Block creation timestamp
  40. pub timestamp: Timestamp,
  41. /// The block's nonce.
  42. /// In PoW, this value changes arbitrarily with mining.
  43. /// In PoS, we can use this value as our block producer ETA.
  44. pub nonce: pallas::Base,
  45. /// Merkle tree of the transactions contained in this block
  46. pub tree: MerkleTree,
  47. }
  48. impl Header {
  49. pub fn new(
  50. previous: blake3::Hash,
  51. epoch: u64,
  52. height: u64,
  53. timestamp: Timestamp,
  54. nonce: pallas::Base,
  55. ) -> Self {
  56. let version = block_version(height);
  57. let tree = MerkleTree::new(1);
  58. Self { version, previous, epoch, height, timestamp, nonce, tree }
  59. }
  60. /// Compute the header's hash
  61. pub fn hash(&self) -> Result<blake3::Hash> {
  62. let mut hasher = blake3::Hasher::new();
  63. self.version.encode(&mut hasher)?;
  64. self.previous.encode(&mut hasher)?;
  65. self.epoch.encode(&mut hasher)?;
  66. self.height.encode(&mut hasher)?;
  67. self.timestamp.encode(&mut hasher)?;
  68. self.nonce.encode(&mut hasher)?;
  69. self.tree.root(0).unwrap().encode(&mut hasher)?;
  70. Ok(hasher.finalize())
  71. }
  72. }
  73. impl Default for Header {
  74. /// Represents the genesis header on current timestamp
  75. fn default() -> Self {
  76. Header::new(
  77. blake3::hash(b"Let there be dark!"),
  78. 0,
  79. 0,
  80. Timestamp::current_time(),
  81. pallas::Base::ZERO,
  82. )
  83. }
  84. }
  85. /// [`Header`] sled tree
  86. const SLED_HEADER_TREE: &[u8] = b"_headers";
  87. /// The `HeaderStore` is a `sled` tree storing all the blockchain's blocks' headers
  88. /// where the key is the headers' hash, and value is the serialized header.
  89. #[derive(Clone)]
  90. pub struct HeaderStore(pub sled::Tree);
  91. impl HeaderStore {
  92. /// Opens a new or existing `HeaderStore` on the given sled database.
  93. pub fn new(db: &sled::Db) -> Result<Self> {
  94. let tree = db.open_tree(SLED_HEADER_TREE)?;
  95. Ok(Self(tree))
  96. }
  97. /// Insert a slice of [`Header`] into the blockstore.
  98. pub fn insert(&self, headers: &[Header]) -> Result<Vec<blake3::Hash>> {
  99. let (batch, ret) = self.insert_batch(headers)?;
  100. self.0.apply_batch(batch)?;
  101. Ok(ret)
  102. }
  103. /// Generate the sled batch corresponding to an insert, so caller
  104. /// can handle the write operation.
  105. /// The header's hash() function output is used as the key,
  106. /// while value is the serialized [`Header`] itself.
  107. /// On success, the function returns the header hashes in the same
  108. /// order, along with the corresponding operation batch.
  109. pub fn insert_batch(&self, headers: &[Header]) -> Result<(sled::Batch, Vec<blake3::Hash>)> {
  110. let mut ret = Vec::with_capacity(headers.len());
  111. let mut batch = sled::Batch::default();
  112. for header in headers {
  113. let headerhash = header.hash()?;
  114. batch.insert(headerhash.as_bytes(), serialize(header));
  115. ret.push(headerhash);
  116. }
  117. Ok((batch, ret))
  118. }
  119. /// Check if the headerstore contains a given headerhash.
  120. pub fn contains(&self, headerhash: &blake3::Hash) -> Result<bool> {
  121. Ok(self.0.contains_key(headerhash.as_bytes())?)
  122. }
  123. /// Fetch given headerhashes from the headerstore.
  124. /// The resulting vector contains `Option`, which is `Some` if the header
  125. /// was found in the headerstore, and otherwise it is `None`, if it has not.
  126. /// The second parameter is a boolean which tells the function to fail in
  127. /// case at least one header was not found.
  128. pub fn get(&self, headerhashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Header>>> {
  129. let mut ret = Vec::with_capacity(headerhashes.len());
  130. for hash in headerhashes {
  131. if let Some(found) = self.0.get(hash.as_bytes())? {
  132. let header = deserialize(&found)?;
  133. ret.push(Some(header));
  134. } else {
  135. if strict {
  136. let s = hash.to_hex().as_str().to_string();
  137. return Err(Error::HeaderNotFound(s))
  138. }
  139. ret.push(None);
  140. }
  141. }
  142. Ok(ret)
  143. }
  144. /// Retrieve all headers from the headerstore in the form of a tuple
  145. /// (`headerhash`, `header`).
  146. /// Be careful as this will try to load everything in memory.
  147. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Header)>> {
  148. let mut headers = vec![];
  149. for header in self.0.iter() {
  150. headers.push(parse_record(header.unwrap())?);
  151. }
  152. Ok(headers)
  153. }
  154. }
  155. /// Overlay structure over a [`HeaderStore`] instance.
  156. pub struct HeaderStoreOverlay(SledDbOverlayPtr);
  157. impl HeaderStoreOverlay {
  158. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  159. overlay.lock().unwrap().open_tree(SLED_HEADER_TREE)?;
  160. Ok(Self(overlay.clone()))
  161. }
  162. /// Insert a slice of [`Header`] into the overlay.
  163. /// The header's hash() function output is used as the key,
  164. /// while value is the serialized [`Header`] itself.
  165. /// On success, the function returns the header hashes in the same order.
  166. pub fn insert(&self, headers: &[Header]) -> Result<Vec<blake3::Hash>> {
  167. let mut ret = Vec::with_capacity(headers.len());
  168. let mut lock = self.0.lock().unwrap();
  169. for header in headers {
  170. let headerhash = header.hash()?;
  171. lock.insert(SLED_HEADER_TREE, headerhash.as_bytes(), &serialize(header))?;
  172. ret.push(headerhash);
  173. }
  174. Ok(ret)
  175. }
  176. /// Fetch given headerhashes from the overlay.
  177. /// The resulting vector contains `Option`, which is `Some` if the header
  178. /// was found in the overlay, and otherwise it is `None`, if it has not.
  179. /// The second parameter is a boolean which tells the function to fail in
  180. /// case at least one header was not found.
  181. pub fn get(&self, headerhashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Header>>> {
  182. let mut ret = Vec::with_capacity(headerhashes.len());
  183. let lock = self.0.lock().unwrap();
  184. for hash in headerhashes {
  185. if let Some(found) = lock.get(SLED_HEADER_TREE, hash.as_bytes())? {
  186. let header = deserialize(&found)?;
  187. ret.push(Some(header));
  188. } else {
  189. if strict {
  190. let s = hash.to_hex().as_str().to_string();
  191. return Err(Error::HeaderNotFound(s))
  192. }
  193. ret.push(None);
  194. }
  195. }
  196. Ok(ret)
  197. }
  198. }