mod.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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},
  22. util::time::Timestamp,
  23. Result,
  24. };
  25. pub mod blockstore;
  26. pub use blockstore::{BlockOrderStore, BlockStore, HeaderStore};
  27. pub mod nfstore;
  28. pub use nfstore::NullifierStore;
  29. pub mod rootstore;
  30. pub use rootstore::RootStore;
  31. pub mod txstore;
  32. pub use txstore::TxStore;
  33. pub mod contractstore;
  34. pub use contractstore::{ContractStateStore, WasmStore};
  35. /// Structure holding all sled trees that define the concept of Blockchain.
  36. #[derive(Clone)]
  37. pub struct Blockchain {
  38. /// Main pointer to the sled db connection
  39. pub sled_db: sled::Db,
  40. /// Headers sled tree
  41. pub headers: HeaderStore,
  42. /// Blocks sled tree
  43. pub blocks: BlockStore,
  44. /// Block order sled tree
  45. pub order: BlockOrderStore,
  46. /// Transactions sled tree
  47. pub transactions: TxStore,
  48. /// Nullifiers sled tree
  49. pub nullifiers: NullifierStore,
  50. /// Merkle roots sled tree
  51. pub merkle_roots: RootStore,
  52. /// Contract states
  53. pub contracts: ContractStateStore,
  54. /// Wasm bincodes
  55. pub wasm_bincode: WasmStore,
  56. }
  57. impl Blockchain {
  58. /// Instantiate a new `Blockchain` with the given `sled` database.
  59. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  60. let headers = HeaderStore::new(db, genesis_ts, genesis_data)?;
  61. let blocks = BlockStore::new(db, genesis_ts, genesis_data)?;
  62. let order = BlockOrderStore::new(db, genesis_ts, genesis_data)?;
  63. let transactions = TxStore::new(db)?;
  64. let nullifiers = NullifierStore::new(db)?;
  65. let merkle_roots = RootStore::new(db)?;
  66. let contracts = ContractStateStore::new(db)?;
  67. let wasm_bincode = WasmStore::new(db)?;
  68. Ok(Self {
  69. sled_db: db.clone(),
  70. headers,
  71. blocks,
  72. order,
  73. transactions,
  74. nullifiers,
  75. merkle_roots,
  76. contracts,
  77. wasm_bincode,
  78. })
  79. }
  80. /// Insert a given slice of [`BlockInfo`] into the blockchain database.
  81. /// This functions wraps all the logic of separating the block into specific
  82. /// data that can be fed into the different trees of the database.
  83. /// Upon success, the functions returns a vector of the block hashes that
  84. /// were given and appended to the ledger.
  85. pub fn add(&self, blocks: &[BlockInfo]) -> Result<Vec<blake3::Hash>> {
  86. let mut ret = Vec::with_capacity(blocks.len());
  87. // TODO: Make db writes here completely atomic
  88. for block in blocks {
  89. // Store transactions
  90. self.transactions.insert(&block.txs)?;
  91. // Store header
  92. self.headers.insert(&[block.header.clone()])?;
  93. // Store block
  94. let blk: Block = Block::from(block.clone());
  95. let blockhash = self.blocks.insert(&[blk])?;
  96. ret.push(blockhash[0]);
  97. // Store block order
  98. self.order.insert(&[block.header.slot], &[blockhash[0]])?;
  99. }
  100. Ok(ret)
  101. }
  102. /// Check if the given [`BlockInfo`] is in the database and all trees.
  103. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  104. let blockhash = match self.order.get(&[block.header.slot], true) {
  105. Ok(v) => v[0].unwrap(),
  106. Err(_) => return Ok(false),
  107. };
  108. // TODO: Check if we have all transactions
  109. // Check provided info produces the same hash
  110. Ok(blockhash == block.blockhash())
  111. }
  112. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them are not found.
  113. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  114. let mut ret = Vec::with_capacity(hashes.len());
  115. let blocks = self.blocks.get(hashes, true)?;
  116. for block in blocks {
  117. let block = block.unwrap();
  118. let headers = self.headers.get(&[block.header], true)?;
  119. // Since we used strict get, its safe to unwrap here
  120. let header = headers[0].clone().unwrap();
  121. let txs = self.transactions.get(&block.txs, true)?;
  122. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  123. let info = BlockInfo::new(header, txs, block.lead_info.clone());
  124. ret.push(info);
  125. }
  126. Ok(ret)
  127. }
  128. /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
  129. pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
  130. debug!("get_blocks_by_slot(): {:?}", slots);
  131. let blockhashes = self.order.get(slots, false)?;
  132. let mut hashes = vec![];
  133. for i in blockhashes.into_iter().flatten() {
  134. hashes.push(i);
  135. }
  136. self.get_blocks_by_hash(&hashes)
  137. }
  138. /// Retrieve n blocks after given start slot.
  139. pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
  140. debug!("get_blocks_after(): {} -> {}", slot, n);
  141. let hashes = self.order.get_after(slot, n)?;
  142. self.get_blocks_by_hash(&hashes)
  143. }
  144. /// Retrieve stored blocks count
  145. pub fn len(&self) -> usize {
  146. self.order.len()
  147. }
  148. /// Retrieve the last block slot and hash.
  149. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  150. self.order.get_last()
  151. }
  152. /// Retrieve last finalized block leader proof hash.
  153. pub fn get_last_proof_hash(&self) -> Result<blake3::Hash> {
  154. let (_, hash) = self.last().unwrap();
  155. let blocks = self.blocks.get(&[hash], true)?;
  156. // Since we used strict get, its safe to unwrap here
  157. let block = blocks[0].clone().unwrap();
  158. let hash = blake3::hash(&serialize(&block.lead_info.proof));
  159. Ok(hash)
  160. }
  161. /// Retrieve last finalized block slot offset
  162. pub fn get_last_offset(&self) -> Result<(u64, u64)> {
  163. let (slot, 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. Ok((slot, block.lead_info.offset))
  168. }
  169. }