mod.rs 20 KB

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