mod.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 std::sync::{Arc, Mutex};
  19. use log::debug;
  20. use darkfi_serial::serialize;
  21. use crate::{
  22. consensus::{Block, BlockInfo, SlotCheckpoint},
  23. tx::Transaction,
  24. util::time::Timestamp,
  25. Result,
  26. };
  27. pub mod block_store;
  28. pub use block_store::{BlockOrderStore, BlockStore, HeaderStore};
  29. pub mod slot_checkpoint_store;
  30. pub use slot_checkpoint_store::{SlotCheckpointStore, SlotCheckpointStoreOverlay};
  31. pub mod tx_store;
  32. pub use tx_store::{PendingTxOrderStore, PendingTxStore, TxStore};
  33. pub mod contract_store;
  34. pub use contract_store::{
  35. ContractStateStore, ContractStateStoreOverlay, WasmStore, WasmStoreOverlay,
  36. };
  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. /// Pending transactions sled tree
  53. pub pending_txs: PendingTxStore,
  54. /// Pending transactions order sled tree
  55. pub pending_txs_order: PendingTxOrderStore,
  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 pending_txs = PendingTxStore::new(db)?;
  70. let pending_txs_order = PendingTxOrderStore::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. pending_txs,
  81. pending_txs_order,
  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!(target: "blockchain", "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!(target: "blockchain", "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. /// Retrieve stored txs count
  155. pub fn txs_len(&self) -> usize {
  156. self.transactions.len()
  157. }
  158. /// Check if blockchain contains any blocks
  159. pub fn is_empty(&self) -> bool {
  160. self.order.len() == 0
  161. }
  162. /// Retrieve the last block slot and hash.
  163. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  164. self.order.get_last()
  165. }
  166. /// Retrieve the last slot checkpoint.
  167. pub fn last_slot_checkpoint(&self) -> Result<SlotCheckpoint> {
  168. self.slot_checkpoints.get_last()
  169. }
  170. /// Retrieve n checkpoints after given start slot.
  171. pub fn get_slot_checkpoints_after(&self, slot: u64, n: u64) -> Result<Vec<SlotCheckpoint>> {
  172. debug!(target: "blockchain", "get_slot_checkpoints_after(): {} -> {}", slot, n);
  173. self.slot_checkpoints.get_after(slot, n)
  174. }
  175. /// Insert a given slice of [`SlotCheckpoint`] into the blockchain database.
  176. pub fn add_slot_checkpoints(&self, slot_checkpoints: &[SlotCheckpoint]) -> Result<()> {
  177. self.slot_checkpoints.insert(slot_checkpoints)
  178. }
  179. /// Retrieve [`SlotCheckpoint`]s by given slots. Does not fail if any of them are not found.
  180. pub fn get_slot_checkpoints_by_slot(
  181. &self,
  182. slots: &[u64],
  183. ) -> Result<Vec<Option<SlotCheckpoint>>> {
  184. debug!(target: "blockchain", "get_slot_checkpoints_by_slot(): {:?}", slots);
  185. self.slot_checkpoints.get(slots, true)
  186. }
  187. /// Check if the given [`SlotCheckpoint`] is in the database and all trees.
  188. pub fn has_slot_checkpoint(&self, slot_checkpoint: &SlotCheckpoint) -> Result<bool> {
  189. Ok(self.slot_checkpoints.get(&[slot_checkpoint.slot], true).is_ok())
  190. }
  191. /// Check if block order for the given slot is in the database.
  192. pub fn has_slot(&self, slot: u64) -> Result<bool> {
  193. let vec = match self.order.get(&[slot], true) {
  194. Ok(v) => v,
  195. Err(_) => return Ok(false),
  196. };
  197. Ok(!vec.is_empty())
  198. }
  199. /// Insert a given slice of pending transactions into the blockchain database.
  200. /// On success, the function returns the transaction hashes in the same order
  201. /// as the input transactions.
  202. pub fn add_pending_txs(&self, txs: &[Transaction]) -> Result<Vec<blake3::Hash>> {
  203. // TODO: Make db writes here completely atomic
  204. let txs_hashes = self.pending_txs.insert(txs)?;
  205. self.pending_txs_order.insert(&txs_hashes)?;
  206. Ok(txs_hashes)
  207. }
  208. /// Retrieve all transactions from the pending tx store.
  209. /// Be careful as this will try to load everything in memory.
  210. pub fn get_pending_txs(&self) -> Result<Vec<Transaction>> {
  211. let txs = self.pending_txs.get_all()?;
  212. let indexes = self.pending_txs_order.get_all()?;
  213. assert_eq!(txs.len(), indexes.len());
  214. let mut ret = Vec::with_capacity(txs.len());
  215. for index in indexes {
  216. ret.push(txs.get(&index.1).unwrap().clone());
  217. }
  218. Ok(ret)
  219. }
  220. /// Remove a given slice of pending transactions from the blockchain database.
  221. pub fn remove_pending_txs(&self, txs: &[Transaction]) -> Result<()> {
  222. let mut txs_hashes = Vec::with_capacity(txs.len());
  223. for tx in txs {
  224. let tx_hash = blake3::hash(&serialize(tx));
  225. txs_hashes.push(tx_hash);
  226. }
  227. let indexes = self.pending_txs_order.get_all()?;
  228. let mut removed_indexes = vec![];
  229. for index in indexes {
  230. if txs_hashes.contains(&index.1) {
  231. removed_indexes.push(index.0);
  232. }
  233. }
  234. // TODO: Make db writes here completely atomic
  235. self.pending_txs.remove(&txs_hashes)?;
  236. self.pending_txs_order.remove(&removed_indexes)?;
  237. Ok(())
  238. }
  239. }
  240. /// Atomic pointer to sled db overlay.
  241. pub type SledDbOverlayPtr = Arc<Mutex<sled_overlay::SledDbOverlay>>;
  242. /// Atomic pointer to blockchain overlay.
  243. pub type BlockchainOverlayPtr = Arc<Mutex<BlockchainOverlay>>;
  244. /// Overlay structure over a [`Blockchain`] instance.
  245. pub struct BlockchainOverlay {
  246. /// Main [`sled_overlay::SledDbOverlay`] to the sled db connection
  247. pub overlay: SledDbOverlayPtr,
  248. /// Slot checkpoints overlay
  249. pub slot_checkpoints: SlotCheckpointStoreOverlay,
  250. /// Contract states overlay
  251. pub contracts: ContractStateStoreOverlay,
  252. /// Wasm bincodes overlay
  253. pub wasm_bincode: WasmStoreOverlay,
  254. }
  255. impl BlockchainOverlay {
  256. /// Instantiate a new `BlockchainOverlay` over the given [`Blockchain`] instance.
  257. pub fn new(blockchain: &Blockchain) -> Result<BlockchainOverlayPtr> {
  258. let overlay = Arc::new(Mutex::new(sled_overlay::SledDbOverlay::new(&blockchain.sled_db)));
  259. let slot_checkpoints = SlotCheckpointStoreOverlay::new(overlay.clone())?;
  260. let contracts = ContractStateStoreOverlay::new(overlay.clone())?;
  261. let wasm_bincode = WasmStoreOverlay::new(overlay.clone())?;
  262. Ok(Arc::new(Mutex::new(Self { overlay, slot_checkpoints, contracts, wasm_bincode })))
  263. }
  264. }