mod.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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_serial::{deserialize, serialize, Decodable};
  22. use crate::{tx::Transaction, util::time::Timestamp, Error, Result};
  23. /// Block related definitions and storage implementations
  24. pub mod block_store;
  25. pub use block_store::{Block, BlockDifficulty, BlockInfo, BlockStore, BlockStoreOverlay};
  26. /// Header definition and storage implementation
  27. pub mod header_store;
  28. pub use header_store::{Header, HeaderStore, HeaderStoreOverlay};
  29. /// Transactions related storage implementations
  30. pub mod tx_store;
  31. pub use tx_store::{TxStore, TxStoreOverlay};
  32. /// Contracts and Wasm storage implementations
  33. pub mod contract_store;
  34. pub use contract_store::{ContractStore, ContractStoreOverlay};
  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. /// Transactions related sled trees
  45. pub transactions: TxStore,
  46. /// Contracts related sled trees
  47. pub contracts: ContractStore,
  48. }
  49. impl Blockchain {
  50. /// Instantiate a new `Blockchain` with the given `sled` database.
  51. pub fn new(db: &sled::Db) -> Result<Self> {
  52. let headers = HeaderStore::new(db)?;
  53. let blocks = BlockStore::new(db)?;
  54. let transactions = TxStore::new(db)?;
  55. let contracts = ContractStore::new(db)?;
  56. Ok(Self { sled_db: db.clone(), headers, blocks, transactions, contracts })
  57. }
  58. /// Insert a given [`BlockInfo`] into the blockchain database.
  59. /// This functions wraps all the logic of separating the block into specific
  60. /// data that can be fed into the different trees of the database.
  61. /// Upon success, the functions returns the block hash that
  62. /// were given and appended to the ledger.
  63. pub fn add_block(&self, block: &BlockInfo) -> Result<blake3::Hash> {
  64. let mut trees = vec![];
  65. let mut batches = vec![];
  66. // Store header
  67. let (headers_batch, _) = self.headers.insert_batch(&[block.header.clone()])?;
  68. trees.push(self.headers.0.clone());
  69. batches.push(headers_batch);
  70. // Store block
  71. let blk: Block = Block::from_block_info(block)?;
  72. let (bocks_batch, block_hashes) = self.blocks.insert_batch(&[blk])?;
  73. let block_hash = block_hashes[0];
  74. let block_hash_vec = [block_hash];
  75. trees.push(self.blocks.main.clone());
  76. batches.push(bocks_batch);
  77. // Store block order
  78. let blocks_order_batch =
  79. self.blocks.insert_batch_order(&[block.header.height], &block_hash_vec)?;
  80. trees.push(self.blocks.order.clone());
  81. batches.push(blocks_order_batch);
  82. // Store transactions
  83. let (txs_batch, txs_hashes) = self.transactions.insert_batch(&block.txs)?;
  84. trees.push(self.transactions.main.clone());
  85. batches.push(txs_batch);
  86. // Store transactions_locations
  87. let txs_locations_batch =
  88. self.transactions.insert_batch_location(&txs_hashes, block.header.height)?;
  89. trees.push(self.transactions.location.clone());
  90. batches.push(txs_locations_batch);
  91. // Perform an atomic transaction over the trees and apply the batches.
  92. self.atomic_write(&trees, &batches)?;
  93. Ok(block_hash)
  94. }
  95. /// Check if the given [`BlockInfo`] is in the database and all trees.
  96. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  97. let blockhash = match self.blocks.get_order(&[block.header.height], true) {
  98. Ok(v) => v[0].unwrap(),
  99. Err(_) => return Ok(false),
  100. };
  101. // Check if we have all transactions
  102. let txs: Vec<blake3::Hash> =
  103. block.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  104. if self.transactions.get(&txs, true).is_err() {
  105. return Ok(false)
  106. }
  107. // Check provided info produces the same hash
  108. Ok(blockhash == block.hash()?)
  109. }
  110. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  111. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  112. let blocks = self.blocks.get(hashes, true)?;
  113. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  114. let ret = self.get_blocks_infos(&blocks)?;
  115. Ok(ret)
  116. }
  117. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  118. /// Fails if any of them is not found
  119. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  120. let mut ret = Vec::with_capacity(blocks.len());
  121. for block in blocks {
  122. let headers = self.headers.get(&[block.header], true)?;
  123. // Since we used strict get, its safe to unwrap here
  124. let header = headers[0].clone().unwrap();
  125. let txs = self.transactions.get(&block.txs, true)?;
  126. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  127. let info = BlockInfo::new(header, txs, block.signature);
  128. ret.push(info);
  129. }
  130. Ok(ret)
  131. }
  132. /// Retrieve [`BlockInfo`]s by given heights. Does not fail if any of them are not found.
  133. pub fn get_blocks_by_heights(&self, heights: &[u64]) -> Result<Vec<BlockInfo>> {
  134. debug!(target: "blockchain", "get_blocks_by_heights(): {:?}", heights);
  135. let blockhashes = self.blocks.get_order(heights, false)?;
  136. let mut hashes = vec![];
  137. for i in blockhashes.into_iter().flatten() {
  138. hashes.push(i);
  139. }
  140. self.get_blocks_by_hash(&hashes)
  141. }
  142. /// Retrieve n blocks after given start block height.
  143. pub fn get_blocks_after(&self, height: u64, n: u64) -> Result<Vec<BlockInfo>> {
  144. debug!(target: "blockchain", "get_blocks_after(): {} -> {}", height, n);
  145. let hashes = self.blocks.get_after(height, n)?;
  146. self.get_blocks_by_hash(&hashes)
  147. }
  148. /// Retrieve stored blocks count
  149. pub fn len(&self) -> usize {
  150. self.blocks.len()
  151. }
  152. /// Retrieve stored txs count
  153. pub fn txs_len(&self) -> usize {
  154. self.transactions.len()
  155. }
  156. /// Check if blockchain contains any blocks
  157. pub fn is_empty(&self) -> bool {
  158. self.blocks.is_empty()
  159. }
  160. /// Retrieve genesis (first) block height and hash.
  161. pub fn genesis(&self) -> Result<(u64, blake3::Hash)> {
  162. self.blocks.get_first()
  163. }
  164. /// Retrieve genesis (first) block info.
  165. pub fn genesis_block(&self) -> Result<BlockInfo> {
  166. let (_, hash) = self.genesis()?;
  167. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  168. }
  169. /// Retrieve the last block height and hash.
  170. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  171. self.blocks.get_last()
  172. }
  173. /// Retrieve the last block info.
  174. pub fn last_block(&self) -> Result<BlockInfo> {
  175. let (_, hash) = self.last()?;
  176. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  177. }
  178. /// Retrieve the last block difficulty. If the tree is empty,
  179. /// returns `BlockDifficulty::genesis` difficulty.
  180. pub fn last_block_difficulty(&self) -> Result<BlockDifficulty> {
  181. if let Some(found) = self.blocks.get_last_difficulty()? {
  182. return Ok(found)
  183. }
  184. let genesis_block = self.genesis_block()?;
  185. Ok(BlockDifficulty::genesis(genesis_block.header.timestamp))
  186. }
  187. /// Check if block order for the given height is in the database.
  188. pub fn has_height(&self, height: u64) -> Result<bool> {
  189. let vec = match self.blocks.get_order(&[height], true) {
  190. Ok(v) => v,
  191. Err(_) => return Ok(false),
  192. };
  193. Ok(!vec.is_empty())
  194. }
  195. /// Insert a given slice of pending transactions into the blockchain database.
  196. /// On success, the function returns the transaction hashes in the same order
  197. /// as the input transactions.
  198. pub fn add_pending_txs(&self, txs: &[Transaction]) -> Result<Vec<blake3::Hash>> {
  199. let (txs_batch, txs_hashes) = self.transactions.insert_batch_pending(txs)?;
  200. let txs_order_batch = self.transactions.insert_batch_pending_order(&txs_hashes)?;
  201. // Perform an atomic transaction over the trees and apply the batches.
  202. let trees = [self.transactions.pending.clone(), self.transactions.pending_order.clone()];
  203. let batches = [txs_batch, txs_order_batch];
  204. self.atomic_write(&trees, &batches)?;
  205. Ok(txs_hashes)
  206. }
  207. /// Retrieve all transactions from the pending tx store.
  208. /// Be careful as this will try to load everything in memory.
  209. pub fn get_pending_txs(&self) -> Result<Vec<Transaction>> {
  210. let txs = self.transactions.get_all_pending()?;
  211. let indexes = self.transactions.get_all_pending_order()?;
  212. if txs.len() != indexes.len() {
  213. return Err(Error::InvalidInputLengths)
  214. }
  215. let mut ret = Vec::with_capacity(txs.len());
  216. for index in indexes {
  217. ret.push(txs.get(&index.1).unwrap().clone());
  218. }
  219. Ok(ret)
  220. }
  221. /// Remove a given slice of pending transactions from the blockchain database.
  222. pub fn remove_pending_txs(&self, txs: &[Transaction]) -> Result<()> {
  223. let txs_hashes: Vec<blake3::Hash> =
  224. txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  225. let indexes = self.transactions.get_all_pending_order()?;
  226. // We could do indexes.iter().map(|x| txs_hashes.contains(x.1)).collect.map(|x| x.0).collect
  227. // but this is faster since we don't do the second iteration
  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. let txs_batch = self.transactions.remove_batch_pending(&txs_hashes);
  235. let txs_order_batch = self.transactions.remove_batch_pending_order(&removed_indexes);
  236. // Perform an atomic transaction over the trees and apply the batches.
  237. let trees = [self.transactions.pending.clone(), self.transactions.pending_order.clone()];
  238. let batches = [txs_batch, txs_order_batch];
  239. self.atomic_write(&trees, &batches)?;
  240. Ok(())
  241. }
  242. /// Auxiliary function to write to multiple trees completely atomic.
  243. fn atomic_write(&self, trees: &[sled::Tree], batches: &[sled::Batch]) -> Result<()> {
  244. if trees.len() != batches.len() {
  245. return Err(Error::InvalidInputLengths)
  246. }
  247. trees.transaction(|trees| {
  248. for (index, tree) in trees.iter().enumerate() {
  249. tree.apply_batch(&batches[index])?;
  250. }
  251. Ok::<(), sled::transaction::ConflictableTransactionError<sled::Error>>(())
  252. })?;
  253. Ok(())
  254. }
  255. /// Retrieve all blocks contained in the blockchain in order.
  256. /// Be careful as this will try to load everything in memory.
  257. pub fn get_all(&self) -> Result<Vec<BlockInfo>> {
  258. let order = self.blocks.get_all_order()?;
  259. let order: Vec<blake3::Hash> = order.iter().map(|x| x.1).collect();
  260. let blocks = self.get_blocks_by_hash(&order)?;
  261. Ok(blocks)
  262. }
  263. }
  264. /// Atomic pointer to sled db overlay.
  265. pub type SledDbOverlayPtr = Arc<Mutex<sled_overlay::SledDbOverlay>>;
  266. /// Atomic pointer to blockchain overlay.
  267. pub type BlockchainOverlayPtr = Arc<Mutex<BlockchainOverlay>>;
  268. /// Overlay structure over a [`Blockchain`] instance.
  269. pub struct BlockchainOverlay {
  270. /// Main [`sled_overlay::SledDbOverlay`] to the sled db connection
  271. pub overlay: SledDbOverlayPtr,
  272. /// Headers overlay
  273. pub headers: HeaderStoreOverlay,
  274. /// Blocks overlay
  275. pub blocks: BlockStoreOverlay,
  276. /// Transactions overlay
  277. pub transactions: TxStoreOverlay,
  278. /// Contract overlay
  279. pub contracts: ContractStoreOverlay,
  280. }
  281. impl BlockchainOverlay {
  282. /// Instantiate a new `BlockchainOverlay` over the given [`Blockchain`] instance.
  283. pub fn new(blockchain: &Blockchain) -> Result<BlockchainOverlayPtr> {
  284. let overlay = Arc::new(Mutex::new(sled_overlay::SledDbOverlay::new(&blockchain.sled_db)));
  285. let headers = HeaderStoreOverlay::new(&overlay)?;
  286. let blocks = BlockStoreOverlay::new(&overlay)?;
  287. let transactions = TxStoreOverlay::new(&overlay)?;
  288. let contracts = ContractStoreOverlay::new(&overlay)?;
  289. Ok(Arc::new(Mutex::new(Self { overlay, headers, blocks, transactions, contracts })))
  290. }
  291. /// Check if blockchain contains any blocks
  292. pub fn is_empty(&self) -> Result<bool> {
  293. self.blocks.is_empty()
  294. }
  295. /// Retrieve the last block height and hash.
  296. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  297. self.blocks.get_last()
  298. }
  299. /// Retrieve the last block info.
  300. pub fn last_block(&self) -> Result<BlockInfo> {
  301. let (_, hash) = self.last()?;
  302. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  303. }
  304. /// Retrieve the last block height.
  305. pub fn last_block_height(&self) -> Result<u64> {
  306. Ok(self.last()?.0)
  307. }
  308. /// Retrieve the last block timestamp.
  309. pub fn last_block_timestamp(&self) -> Result<Timestamp> {
  310. let (_, hash) = self.last()?;
  311. Ok(self.get_blocks_by_hash(&[hash])?[0].header.timestamp)
  312. }
  313. /// Insert a given [`BlockInfo`] into the overlay.
  314. /// This functions wraps all the logic of separating the block into specific
  315. /// data that can be fed into the different trees of the overlay.
  316. /// Upon success, the functions returns the block hash that
  317. /// were given and appended to the overlay.
  318. /// Since we are adding to the overlay, we don't need to exeucte
  319. /// the writes atomically.
  320. pub fn add_block(&self, block: &BlockInfo) -> Result<blake3::Hash> {
  321. // Store header
  322. self.headers.insert(&[block.header.clone()])?;
  323. // Store block
  324. let blk: Block = Block::from_block_info(block)?;
  325. let txs_hashes = blk.txs.clone();
  326. let block_hash = self.blocks.insert(&[blk])?[0];
  327. let block_hash_vec = [block_hash];
  328. // Store block order
  329. self.blocks.insert_order(&[block.header.height], &block_hash_vec)?;
  330. // Store transactions
  331. self.transactions.insert(&block.txs)?;
  332. // Store transactions locations
  333. self.transactions.insert_location(&txs_hashes, block.header.height)?;
  334. Ok(block_hash)
  335. }
  336. /// Check if the given [`BlockInfo`] is in the database and all trees.
  337. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  338. let blockhash = match self.blocks.get_order(&[block.header.height], true) {
  339. Ok(v) => v[0].unwrap(),
  340. Err(_) => return Ok(false),
  341. };
  342. // Check if we have all transactions
  343. let txs: Vec<blake3::Hash> =
  344. block.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  345. if self.transactions.get(&txs, true).is_err() {
  346. return Ok(false)
  347. }
  348. // Check provided info produces the same hash
  349. Ok(blockhash == block.hash()?)
  350. }
  351. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  352. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  353. let blocks = self.blocks.get(hashes, true)?;
  354. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  355. let ret = self.get_blocks_infos(&blocks)?;
  356. Ok(ret)
  357. }
  358. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  359. /// Fails if any of them is not found
  360. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  361. let mut ret = Vec::with_capacity(blocks.len());
  362. for block in blocks {
  363. let headers = self.headers.get(&[block.header], true)?;
  364. // Since we used strict get, its safe to unwrap here
  365. let header = headers[0].clone().unwrap();
  366. let txs = self.transactions.get(&block.txs, true)?;
  367. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  368. let info = BlockInfo::new(header, txs, block.signature);
  369. ret.push(info);
  370. }
  371. Ok(ret)
  372. }
  373. /// Retrieve [`Block`]s by given hashes and return their transactions hashes.
  374. pub fn get_blocks_txs_hashes(&self, hashes: &[blake3::Hash]) -> Result<Vec<blake3::Hash>> {
  375. let blocks = self.blocks.get(hashes, true)?;
  376. let mut ret = vec![];
  377. for block in blocks {
  378. ret.extend_from_slice(&block.unwrap().txs);
  379. }
  380. Ok(ret)
  381. }
  382. /// Checkpoint overlay so we can revert to it, if needed.
  383. pub fn checkpoint(&self) {
  384. self.overlay.lock().unwrap().checkpoint();
  385. }
  386. /// Revert to current overlay checkpoint.
  387. pub fn revert_to_checkpoint(&self) -> Result<()> {
  388. self.overlay.lock().unwrap().revert_to_checkpoint()?;
  389. Ok(())
  390. }
  391. /// Auxiliary function to create a full clone using SledDbOverlay::clone,
  392. /// generating new pointers for the underlying overlays.
  393. pub fn full_clone(&self) -> Result<BlockchainOverlayPtr> {
  394. let overlay = Arc::new(Mutex::new(self.overlay.lock().unwrap().clone()));
  395. let headers = HeaderStoreOverlay::new(&overlay)?;
  396. let blocks = BlockStoreOverlay::new(&overlay)?;
  397. let transactions = TxStoreOverlay::new(&overlay)?;
  398. let contracts = ContractStoreOverlay::new(&overlay)?;
  399. Ok(Arc::new(Mutex::new(Self { overlay, headers, blocks, transactions, contracts })))
  400. }
  401. }
  402. /// Parse a sled record with a u64 keyin the form of a tuple (`key`, `value`).
  403. pub fn parse_u64_key_record<T: Decodable>(record: (sled::IVec, sled::IVec)) -> Result<(u64, T)> {
  404. let key_bytes: [u8; 8] = record.0.as_ref().try_into().unwrap();
  405. let key = u64::from_be_bytes(key_bytes);
  406. let value = deserialize(&record.1)?;
  407. Ok((key, value))
  408. }
  409. /// Parse a sled record in the form of a tuple (`key`, `value`).
  410. pub fn parse_record<T1: Decodable, T2: Decodable>(
  411. record: (sled::IVec, sled::IVec),
  412. ) -> Result<(T1, T2)> {
  413. let key = deserialize(&record.0)?;
  414. let value = deserialize(&record.1)?;
  415. Ok((key, value))
  416. }