mod.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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::serialize;
  19. use log::debug;
  20. use crate::{
  21. consensus::{Block, BlockInfo, SlotCheckpoint},
  22. util::time::Timestamp,
  23. Error, Result,
  24. };
  25. pub mod blockstore;
  26. pub use blockstore::{BlockOrderStore, BlockStore, HeaderStore};
  27. pub mod slotcheckpointstore;
  28. pub use slotcheckpointstore::SlotCheckpointStore;
  29. pub mod nfstore;
  30. pub use nfstore::NullifierStore;
  31. pub mod rootstore;
  32. pub use rootstore::RootStore;
  33. pub mod txstore;
  34. pub use txstore::TxStore;
  35. pub mod contractstore;
  36. pub use contractstore::{ContractStateStore, WasmStore};
  37. /// Structure holding all sled trees that define the concept of Blockchain.
  38. #[derive(Clone)]
  39. pub struct Blockchain {
  40. /// Main pointer to the sled db connection
  41. pub sled_db: sled::Db,
  42. /// Headers sled tree
  43. pub headers: HeaderStore,
  44. /// Blocks sled tree
  45. pub blocks: BlockStore,
  46. /// Block order sled tree
  47. pub order: BlockOrderStore,
  48. /// Slot checkpoints sled tree
  49. pub slot_checkpoints: SlotCheckpointStore,
  50. /// Transactions sled tree
  51. pub transactions: TxStore,
  52. /// Nullifiers sled tree
  53. pub nullifiers: NullifierStore,
  54. /// Merkle roots sled tree
  55. pub merkle_roots: RootStore,
  56. /// Contract states
  57. pub contracts: ContractStateStore,
  58. /// Wasm bincodes
  59. pub wasm_bincode: WasmStore,
  60. }
  61. impl Blockchain {
  62. /// Instantiate a new `Blockchain` with the given `sled` database.
  63. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  64. let headers = HeaderStore::new(db, genesis_ts, genesis_data)?;
  65. let blocks = BlockStore::new(db, genesis_ts, genesis_data)?;
  66. let order = BlockOrderStore::new(db, genesis_ts, genesis_data)?;
  67. let slot_checkpoints = SlotCheckpointStore::new(db)?;
  68. let transactions = TxStore::new(db)?;
  69. let nullifiers = NullifierStore::new(db)?;
  70. let merkle_roots = RootStore::new(db)?;
  71. let contracts = ContractStateStore::new(db)?;
  72. let wasm_bincode = WasmStore::new(db)?;
  73. Ok(Self {
  74. sled_db: db.clone(),
  75. headers,
  76. blocks,
  77. order,
  78. slot_checkpoints,
  79. transactions,
  80. nullifiers,
  81. merkle_roots,
  82. contracts,
  83. wasm_bincode,
  84. })
  85. }
  86. /// Insert a given slice of [`BlockInfo`] into the blockchain database.
  87. /// This functions wraps all the logic of separating the block into specific
  88. /// data that can be fed into the different trees of the database.
  89. /// Upon success, the functions returns a vector of the block hashes that
  90. /// were given and appended to the ledger.
  91. pub fn add(&self, blocks: &[BlockInfo]) -> Result<Vec<blake3::Hash>> {
  92. let mut ret = Vec::with_capacity(blocks.len());
  93. // TODO: Make db writes here completely atomic
  94. for block in blocks {
  95. // Store transactions
  96. self.transactions.insert(&block.txs)?;
  97. // Store header
  98. self.headers.insert(&[block.header.clone()])?;
  99. // Store block
  100. let blk: Block = Block::from(block.clone());
  101. let blockhash = self.blocks.insert(&[blk])?;
  102. ret.push(blockhash[0]);
  103. // Store block order
  104. self.order.insert(&[block.header.slot], &[blockhash[0]])?;
  105. }
  106. Ok(ret)
  107. }
  108. /// Check if the given [`BlockInfo`] is in the database and all trees.
  109. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  110. let blockhash = match self.order.get(&[block.header.slot], true) {
  111. Ok(v) => v[0].unwrap(),
  112. Err(_) => return Ok(false),
  113. };
  114. // TODO: Check if we have all transactions
  115. // Check provided info produces the same hash
  116. Ok(blockhash == block.blockhash())
  117. }
  118. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them are not found.
  119. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  120. let mut ret = Vec::with_capacity(hashes.len());
  121. let blocks = self.blocks.get(hashes, true)?;
  122. for block in blocks {
  123. let block = block.unwrap();
  124. let headers = self.headers.get(&[block.header], true)?;
  125. // Since we used strict get, its safe to unwrap here
  126. let header = headers[0].clone().unwrap();
  127. let txs = self.transactions.get(&block.txs, true)?;
  128. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  129. let info = BlockInfo::new(header, txs, block.lead_info.clone());
  130. ret.push(info);
  131. }
  132. Ok(ret)
  133. }
  134. /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
  135. pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
  136. debug!("get_blocks_by_slot(): {:?}", slots);
  137. let blockhashes = self.order.get(slots, false)?;
  138. let mut hashes = vec![];
  139. for i in blockhashes.into_iter().flatten() {
  140. hashes.push(i);
  141. }
  142. self.get_blocks_by_hash(&hashes)
  143. }
  144. /// Retrieve n blocks after given start slot.
  145. pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
  146. debug!("get_blocks_after(): {} -> {}", slot, n);
  147. let hashes = self.order.get_after(slot, n)?;
  148. self.get_blocks_by_hash(&hashes)
  149. }
  150. /// Retrieve stored blocks count
  151. pub fn len(&self) -> usize {
  152. self.order.len()
  153. }
  154. pub fn is_empty(&self) -> bool {
  155. self.order.len() == 0
  156. }
  157. /// Retrieve the last block slot and hash.
  158. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  159. self.order.get_last()
  160. }
  161. /// Retrieve last finalized block leader proof hash.
  162. pub fn get_last_proof_hash(&self) -> Result<blake3::Hash> {
  163. let (_, hash) = self.last().unwrap();
  164. let blocks = self.blocks.get(&[hash], true)?;
  165. // Since we used strict get, its safe to unwrap here
  166. let block = blocks[0].clone().unwrap();
  167. let hash = blake3::hash(&serialize(&block.lead_info.proof));
  168. Ok(hash)
  169. }
  170. pub fn get_proof_hash_by_slot(&self, slot: u64) -> Result<blake3::Hash> {
  171. let blocks = self.get_blocks_by_slot(&[slot]).unwrap();
  172. if blocks.is_empty() {
  173. return Err(Error::BlockNotFound("block not found".to_string()))
  174. }
  175. // Since we used strict get, its safe to unwrap here
  176. let block = blocks[0].clone();
  177. let hash = blake3::hash(&serialize(&block.lead_info.proof));
  178. Ok(hash)
  179. }
  180. /// Retrieve last finalized block slot offset
  181. pub fn get_last_offset(&self) -> Result<(u64, u64)> {
  182. let (slot, hash) = self.last().unwrap();
  183. let blocks = self.blocks.get(&[hash], true)?;
  184. // Since we used strict get, its safe to unwrap here
  185. let block = blocks[0].clone().unwrap();
  186. Ok((slot, block.lead_info.offset))
  187. }
  188. /// Retrieve the last slot checkpoint.
  189. pub fn last_slot_checkpoint(&self) -> Result<SlotCheckpoint> {
  190. self.slot_checkpoints.get_last()
  191. }
  192. /// Retrieve n checkpoints after given start slot.
  193. pub fn get_slot_checkpoints_after(&self, slot: u64, n: u64) -> Result<Vec<SlotCheckpoint>> {
  194. debug!("get_slot_checkpoints_after(): {} -> {}", slot, n);
  195. self.slot_checkpoints.get_after(slot, n)
  196. }
  197. /// Insert a given slice of [`SlotCheckpoint`] into the blockchain database.
  198. pub fn add_slot_checkpoints(&self, slot_checkpoints: &[SlotCheckpoint]) -> Result<()> {
  199. self.slot_checkpoints.insert(slot_checkpoints)
  200. }
  201. /// Retrieve [`SlotCheckpoint`]s by given slots. Does not fail if any of them are not found.
  202. pub fn get_slot_checkpoints_by_slot(
  203. &self,
  204. slots: &[u64],
  205. ) -> Result<Vec<Option<SlotCheckpoint>>> {
  206. debug!("get_slot_checkpoints_by_slot(): {:?}", slots);
  207. self.slot_checkpoints.get(slots, true)
  208. }
  209. /// Check if the given [`SlotCheckpoint`] is in the database and all trees.
  210. pub fn has_slot_checkpoint(&self, slot_checkpoint: &SlotCheckpoint) -> Result<bool> {
  211. if let Err(_) = self.slot_checkpoints.get(&[slot_checkpoint.slot], true) {
  212. return Ok(false)
  213. }
  214. Ok(true)
  215. }
  216. }