mod.rs 19 KB

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