mod.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 sled::Transactional;
  21. use darkfi_sdk::blockchain::Slot;
  22. use darkfi_serial::{deserialize, serialize, Decodable};
  23. use crate::{tx::Transaction, Error, Result};
  24. /// Block related definitions and storage implementations
  25. pub mod block_store;
  26. pub use block_store::{
  27. Block, BlockInfo, BlockOrderStore, BlockOrderStoreOverlay, BlockStore, BlockStoreOverlay,
  28. };
  29. /// Header definition and storage implementation
  30. pub mod header_store;
  31. pub use header_store::{Header, HeaderStore, HeaderStoreOverlay};
  32. /// Slots storage implementation
  33. pub mod slot_store;
  34. pub use slot_store::{SlotStore, SlotStoreOverlay};
  35. /// Transactions related storage implementations
  36. pub mod tx_store;
  37. pub use tx_store::{PendingTxOrderStore, PendingTxStore, TxStore, TxStoreOverlay};
  38. /// Contracts and Wasm storage implementations
  39. pub mod contract_store;
  40. pub use contract_store::{
  41. ContractStateStore, ContractStateStoreOverlay, WasmStore, WasmStoreOverlay,
  42. };
  43. /// Structure holding all sled trees that define the concept of Blockchain.
  44. #[derive(Clone)]
  45. pub struct Blockchain {
  46. /// Main pointer to the sled db connection
  47. pub sled_db: sled::Db,
  48. /// Headers sled tree
  49. pub headers: HeaderStore,
  50. /// Blocks sled tree
  51. pub blocks: BlockStore,
  52. /// Block order sled tree
  53. pub order: BlockOrderStore,
  54. /// Slot sled tree
  55. pub slots: SlotStore,
  56. /// Transactions sled tree
  57. pub transactions: TxStore,
  58. /// Pending transactions sled tree
  59. pub pending_txs: PendingTxStore,
  60. /// Pending transactions order sled tree
  61. pub pending_txs_order: PendingTxOrderStore,
  62. /// Contract states
  63. pub contracts: ContractStateStore,
  64. /// Wasm bincodes
  65. pub wasm_bincode: WasmStore,
  66. }
  67. impl Blockchain {
  68. /// Instantiate a new `Blockchain` with the given `sled` database.
  69. pub fn new(db: &sled::Db) -> Result<Self> {
  70. let headers = HeaderStore::new(db)?;
  71. let blocks = BlockStore::new(db)?;
  72. let order = BlockOrderStore::new(db)?;
  73. let slots = SlotStore::new(db)?;
  74. let transactions = TxStore::new(db)?;
  75. let pending_txs = PendingTxStore::new(db)?;
  76. let pending_txs_order = PendingTxOrderStore::new(db)?;
  77. let contracts = ContractStateStore::new(db)?;
  78. let wasm_bincode = WasmStore::new(db)?;
  79. Ok(Self {
  80. sled_db: db.clone(),
  81. headers,
  82. blocks,
  83. order,
  84. slots,
  85. transactions,
  86. pending_txs,
  87. pending_txs_order,
  88. contracts,
  89. wasm_bincode,
  90. })
  91. }
  92. /// A blockchain is considered valid, when every block is valid,
  93. /// based on validate_block checks.
  94. /// Be careful as this will try to load everything in memory.
  95. pub fn validate(&self) -> Result<()> {
  96. // We use block order store here so we have all blocks in order
  97. let blocks = self.order.get_all()?;
  98. for (index, block) in blocks[1..].iter().enumerate() {
  99. let full_blocks = self.get_blocks_by_hash(&[blocks[index].1, block.1])?;
  100. full_blocks[1].validate(&full_blocks[0])?;
  101. }
  102. Ok(())
  103. }
  104. /// Insert a given [`BlockInfo`] into the blockchain database.
  105. /// This functions wraps all the logic of separating the block into specific
  106. /// data that can be fed into the different trees of the database.
  107. /// Upon success, the functions returns the block hash that
  108. /// were given and appended to the ledger.
  109. pub fn add_block(&self, block: &BlockInfo) -> Result<blake3::Hash> {
  110. let mut trees = vec![];
  111. let mut batches = vec![];
  112. // Store transactions
  113. let (txs_batch, _) = self.transactions.insert_batch(&block.txs)?;
  114. trees.push(self.transactions.0.clone());
  115. batches.push(txs_batch);
  116. // Store header
  117. let (headers_batch, _) = self.headers.insert_batch(&[block.header.clone()])?;
  118. trees.push(self.headers.0.clone());
  119. batches.push(headers_batch);
  120. // Store block
  121. let blk: Block = Block::from(block.clone());
  122. let (bocks_batch, block_hashes) = self.blocks.insert_batch(&[blk])?;
  123. let block_hash = block_hashes[0];
  124. trees.push(self.blocks.0.clone());
  125. batches.push(bocks_batch);
  126. // Store block order
  127. let blocks_order_batch = self.order.insert_batch(&[block.header.slot], &[block_hash])?;
  128. trees.push(self.order.0.clone());
  129. batches.push(blocks_order_batch);
  130. // Store slot checkpoints
  131. let slots_batch = self.slots.insert_batch(&block.slots)?;
  132. trees.push(self.slots.0.clone());
  133. batches.push(slots_batch);
  134. // Perform an atomic transaction over the trees and apply the batches.
  135. self.atomic_write(&trees, &batches)?;
  136. Ok(block_hash)
  137. }
  138. /// Check if the given [`BlockInfo`] is in the database and all trees.
  139. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  140. let blockhash = match self.order.get(&[block.header.slot], true) {
  141. Ok(v) => v[0].unwrap(),
  142. Err(_) => return Ok(false),
  143. };
  144. // Check if we have all transactions
  145. let txs: Vec<blake3::Hash> =
  146. block.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  147. if self.transactions.get(&txs, true).is_err() {
  148. return Ok(false)
  149. }
  150. // Check if we have all slots
  151. let slots: Vec<u64> = block.slots.iter().map(|x| x.id).collect();
  152. if self.slots.get(&slots, true).is_err() {
  153. return Ok(false)
  154. }
  155. // Check provided info produces the same hash
  156. Ok(blockhash == block.blockhash())
  157. }
  158. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  159. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  160. let blocks = self.blocks.get(hashes, true)?;
  161. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  162. let ret = self.get_blocks_infos(&blocks)?;
  163. Ok(ret)
  164. }
  165. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  166. /// Fails if any of them is not found
  167. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  168. let mut ret = Vec::with_capacity(blocks.len());
  169. for block in blocks {
  170. let headers = self.headers.get(&[block.header], true)?;
  171. // Since we used strict get, its safe to unwrap here
  172. let header = headers[0].clone().unwrap();
  173. let txs = self.transactions.get(&block.txs, true)?;
  174. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  175. let slots = self.slots.get(&block.slots, true)?;
  176. let slots = slots.iter().map(|x| x.clone().unwrap()).collect();
  177. let info = BlockInfo::new(header, txs, block.producer.clone(), slots);
  178. ret.push(info);
  179. }
  180. Ok(ret)
  181. }
  182. /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
  183. pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
  184. debug!(target: "blockchain", "get_blocks_by_slot(): {:?}", slots);
  185. let blockhashes = self.order.get(slots, false)?;
  186. let mut hashes = vec![];
  187. for i in blockhashes.into_iter().flatten() {
  188. hashes.push(i);
  189. }
  190. self.get_blocks_by_hash(&hashes)
  191. }
  192. /// Retrieve n blocks after given start slot.
  193. pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
  194. debug!(target: "blockchain", "get_blocks_after(): {} -> {}", slot, n);
  195. let hashes = self.order.get_after(slot, n)?;
  196. self.get_blocks_by_hash(&hashes)
  197. }
  198. /// Retrieve stored blocks count
  199. pub fn len(&self) -> usize {
  200. self.order.len()
  201. }
  202. /// Retrieve stored txs count
  203. pub fn txs_len(&self) -> usize {
  204. self.transactions.len()
  205. }
  206. /// Check if blockchain contains any blocks
  207. pub fn is_empty(&self) -> bool {
  208. self.order.is_empty()
  209. }
  210. /// Retrieve genesis (first) block slot and hash.
  211. pub fn genesis(&self) -> Result<(u64, blake3::Hash)> {
  212. self.order.get_first()
  213. }
  214. /// Retrieve the last block slot and hash.
  215. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  216. self.order.get_last()
  217. }
  218. /// Retrieve the last block info.
  219. pub fn last_block(&self) -> Result<BlockInfo> {
  220. let (_, hash) = self.last()?;
  221. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  222. }
  223. /// Retrieve the last slot.
  224. pub fn last_slot(&self) -> Result<Slot> {
  225. self.slots.get_last()
  226. }
  227. /// Retrieve n slots after given start slot.
  228. pub fn get_slots_after(&self, slot: u64, n: u64) -> Result<Vec<Slot>> {
  229. debug!(target: "blockchain", "get_slots_after(): {} -> {}", slot, n);
  230. self.slots.get_after(slot, n)
  231. }
  232. /// Retrieve [`Slot`]s by given ids. Does not fail if any of them are not found.
  233. pub fn get_slots_by_id(&self, ids: &[u64]) -> Result<Vec<Option<Slot>>> {
  234. debug!(target: "blockchain", "get_slots_by_id(): {:?}", ids);
  235. self.slots.get(ids, true)
  236. }
  237. /// Check if the given [`Slot`] is in the database and all trees.
  238. pub fn has_slot(&self, slot: &Slot) -> Result<bool> {
  239. Ok(self.slots.get(&[slot.id], true).is_ok())
  240. }
  241. /// Check if block order for the given slot is in the database.
  242. pub fn has_slot_order(&self, slot: u64) -> Result<bool> {
  243. let vec = match self.order.get(&[slot], true) {
  244. Ok(v) => v,
  245. Err(_) => return Ok(false),
  246. };
  247. Ok(!vec.is_empty())
  248. }
  249. /// Insert a given slice of pending transactions into the blockchain database.
  250. /// On success, the function returns the transaction hashes in the same order
  251. /// as the input transactions.
  252. pub fn add_pending_txs(&self, txs: &[Transaction]) -> Result<Vec<blake3::Hash>> {
  253. let (txs_batch, txs_hashes) = self.pending_txs.insert_batch(txs)?;
  254. let txs_order_batch = self.pending_txs_order.insert_batch(&txs_hashes)?;
  255. // Perform an atomic transaction over the trees and apply the batches.
  256. let trees = [self.pending_txs.0.clone(), self.pending_txs_order.0.clone()];
  257. let batches = [txs_batch, txs_order_batch];
  258. self.atomic_write(&trees, &batches)?;
  259. Ok(txs_hashes)
  260. }
  261. /// Retrieve all transactions from the pending tx store.
  262. /// Be careful as this will try to load everything in memory.
  263. pub fn get_pending_txs(&self) -> Result<Vec<Transaction>> {
  264. let txs = self.pending_txs.get_all()?;
  265. let indexes = self.pending_txs_order.get_all()?;
  266. if txs.len() != indexes.len() {
  267. return Err(Error::InvalidInputLengths)
  268. }
  269. let mut ret = Vec::with_capacity(txs.len());
  270. for index in indexes {
  271. ret.push(txs.get(&index.1).unwrap().clone());
  272. }
  273. Ok(ret)
  274. }
  275. /// Remove a given slice of pending transactions from the blockchain database.
  276. pub fn remove_pending_txs(&self, txs: &[Transaction]) -> Result<()> {
  277. let txs_hashes: Vec<blake3::Hash> =
  278. txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  279. let indexes = self.pending_txs_order.get_all()?;
  280. // We could do indexes.iter().map(|x| txs_hashes.contains(x.1)).collect.map(|x| x.0).collect but this is faster
  281. // since we don't do the second iteration
  282. let mut removed_indexes = vec![];
  283. for index in indexes {
  284. if txs_hashes.contains(&index.1) {
  285. removed_indexes.push(index.0);
  286. }
  287. }
  288. let txs_batch = self.pending_txs.remove_batch(&txs_hashes);
  289. let txs_order_batch = self.pending_txs_order.remove_batch(&removed_indexes);
  290. // Perform an atomic transaction over the trees and apply the batches.
  291. let trees = [self.pending_txs.0.clone(), self.pending_txs_order.0.clone()];
  292. let batches = [txs_batch, txs_order_batch];
  293. self.atomic_write(&trees, &batches)?;
  294. Ok(())
  295. }
  296. /// Auxiliary function to write to multiple trees completely atomic.
  297. fn atomic_write(&self, trees: &[sled::Tree], batches: &[sled::Batch]) -> Result<()> {
  298. if trees.len() != batches.len() {
  299. return Err(Error::InvalidInputLengths)
  300. }
  301. trees.transaction(|trees| {
  302. for (index, tree) in trees.iter().enumerate() {
  303. tree.apply_batch(&batches[index])?;
  304. }
  305. Ok::<(), sled::transaction::ConflictableTransactionError<sled::Error>>(())
  306. })?;
  307. Ok(())
  308. }
  309. }
  310. /// Atomic pointer to sled db overlay.
  311. pub type SledDbOverlayPtr = Arc<Mutex<sled_overlay::SledDbOverlay>>;
  312. /// Atomic pointer to blockchain overlay.
  313. pub type BlockchainOverlayPtr = Arc<Mutex<BlockchainOverlay>>;
  314. /// Overlay structure over a [`Blockchain`] instance.
  315. pub struct BlockchainOverlay {
  316. /// Main [`sled_overlay::SledDbOverlay`] to the sled db connection
  317. pub overlay: SledDbOverlayPtr,
  318. /// Headers overlay
  319. pub headers: HeaderStoreOverlay,
  320. /// Blocks overlay
  321. pub blocks: BlockStoreOverlay,
  322. /// Block order overlay
  323. pub order: BlockOrderStoreOverlay,
  324. /// Slots overlay
  325. pub slots: SlotStoreOverlay,
  326. /// Transactions overlay
  327. pub transactions: TxStoreOverlay,
  328. /// Contract states overlay
  329. pub contracts: ContractStateStoreOverlay,
  330. /// Wasm bincodes overlay
  331. pub wasm_bincode: WasmStoreOverlay,
  332. }
  333. impl BlockchainOverlay {
  334. /// Instantiate a new `BlockchainOverlay` over the given [`Blockchain`] instance.
  335. pub fn new(blockchain: &Blockchain) -> Result<BlockchainOverlayPtr> {
  336. let overlay = Arc::new(Mutex::new(sled_overlay::SledDbOverlay::new(&blockchain.sled_db)));
  337. let headers = HeaderStoreOverlay::new(overlay.clone())?;
  338. let blocks = BlockStoreOverlay::new(overlay.clone())?;
  339. let order = BlockOrderStoreOverlay::new(overlay.clone())?;
  340. let slots = SlotStoreOverlay::new(overlay.clone())?;
  341. let transactions = TxStoreOverlay::new(overlay.clone())?;
  342. let contracts = ContractStateStoreOverlay::new(overlay.clone())?;
  343. let wasm_bincode = WasmStoreOverlay::new(overlay.clone())?;
  344. Ok(Arc::new(Mutex::new(Self {
  345. overlay,
  346. headers,
  347. blocks,
  348. order,
  349. slots,
  350. transactions,
  351. contracts,
  352. wasm_bincode,
  353. })))
  354. }
  355. /// Check if blockchain contains any blocks
  356. pub fn is_empty(&self) -> Result<bool> {
  357. self.order.is_empty()
  358. }
  359. /// Retrieve the last block slot and hash.
  360. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  361. self.order.get_last()
  362. }
  363. /// Retrieve the last block info.
  364. pub fn last_block(&self) -> Result<BlockInfo> {
  365. let (_, hash) = self.last()?;
  366. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  367. }
  368. /// Insert a given [`BlockInfo`] into the overlay.
  369. /// This functions wraps all the logic of separating the block into specific
  370. /// data that can be fed into the different trees of the overlay.
  371. /// Upon success, the functions returns the block hash that
  372. /// were given and appended to the overlay.
  373. /// Since we are adding to the overlay, we don't need to exeucte
  374. /// the writes atomically.
  375. pub fn add_block(&self, block: &BlockInfo) -> Result<blake3::Hash> {
  376. // Store transactions
  377. self.transactions.insert(&block.txs)?;
  378. // Store header
  379. self.headers.insert(&[block.header.clone()])?;
  380. // Store block
  381. let blk: Block = Block::from(block.clone());
  382. let block_hash = self.blocks.insert(&[blk])?[0];
  383. // Store block order
  384. self.order.insert(&[block.header.slot], &[block_hash])?;
  385. // Store slot checkpoints
  386. self.slots.insert(&block.slots)?;
  387. Ok(block_hash)
  388. }
  389. /// Check if the given [`BlockInfo`] is in the database and all trees.
  390. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  391. let blockhash = match self.order.get(&[block.header.slot], true) {
  392. Ok(v) => v[0].unwrap(),
  393. Err(_) => return Ok(false),
  394. };
  395. // Check if we have all transactions
  396. let txs: Vec<blake3::Hash> =
  397. block.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  398. if self.transactions.get(&txs, true).is_err() {
  399. return Ok(false)
  400. }
  401. // Check if we have all slots
  402. let slots: Vec<u64> = block.slots.iter().map(|x| x.id).collect();
  403. if self.slots.get(&slots, true).is_err() {
  404. return Ok(false)
  405. }
  406. // Check provided info produces the same hash
  407. Ok(blockhash == block.blockhash())
  408. }
  409. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  410. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  411. let blocks = self.blocks.get(hashes, true)?;
  412. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  413. let ret = self.get_blocks_infos(&blocks)?;
  414. Ok(ret)
  415. }
  416. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  417. /// Fails if any of them is not found
  418. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  419. let mut ret = Vec::with_capacity(blocks.len());
  420. for block in blocks {
  421. let headers = self.headers.get(&[block.header], true)?;
  422. // Since we used strict get, its safe to unwrap here
  423. let header = headers[0].clone().unwrap();
  424. let txs = self.transactions.get(&block.txs, true)?;
  425. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  426. let slots = self.slots.get(&block.slots, true)?;
  427. let slots = slots.iter().map(|x| x.clone().unwrap()).collect();
  428. let info = BlockInfo::new(header, txs, block.producer.clone(), slots);
  429. ret.push(info);
  430. }
  431. Ok(ret)
  432. }
  433. /// Checkpoint overlay so we can revert to it, if needed.
  434. pub fn checkpoint(&self) {
  435. self.overlay.lock().unwrap().checkpoint();
  436. }
  437. /// Revert to current overlay checkpoint.
  438. pub fn revert_to_checkpoint(&self) -> Result<()> {
  439. self.overlay.lock().unwrap().revert_to_checkpoint()?;
  440. Ok(())
  441. }
  442. }
  443. /// Parse a sled record in the form of a tuple (`key`, `value`).
  444. pub fn parse_record<T1: Decodable, T2: Decodable>(
  445. record: (sled::IVec, sled::IVec),
  446. ) -> Result<(T1, T2)> {
  447. let key = deserialize(&record.0)?;
  448. let value = deserialize(&record.1)?;
  449. Ok((key, value))
  450. }