mod.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 darkfi_sdk::{monotree::Monotree, tx::TransactionHash};
  20. use log::debug;
  21. use sled_overlay::{sled, sled::Transactional};
  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, BlockInfo, BlockStore, BlockStoreOverlay, SLED_BLOCK_DIFFICULTY_TREE,
  27. SLED_BLOCK_ORDER_TREE, SLED_BLOCK_STATE_INVERSE_DIFF_TREE, SLED_BLOCK_TREE,
  28. };
  29. /// Header definition and storage implementation
  30. pub mod header_store;
  31. pub use header_store::{
  32. Header, HeaderHash, HeaderStore, HeaderStoreOverlay, SLED_HEADER_TREE, SLED_SYNC_HEADER_TREE,
  33. };
  34. /// Transactions related storage implementations
  35. pub mod tx_store;
  36. pub use tx_store::{
  37. TxStore, TxStoreOverlay, SLED_PENDING_TX_ORDER_TREE, SLED_PENDING_TX_TREE,
  38. SLED_TX_LOCATION_TREE, SLED_TX_TREE,
  39. };
  40. /// Contracts and Wasm storage implementations
  41. pub mod contract_store;
  42. pub use contract_store::{
  43. ContractStore, ContractStoreOverlay, SLED_BINCODE_TREE, SLED_CONTRACTS_TREE,
  44. };
  45. /// Monero definitions needed for merge mining
  46. pub mod monero;
  47. /// Structure holding all sled trees that define the concept of Blockchain.
  48. #[derive(Clone)]
  49. pub struct Blockchain {
  50. /// Main pointer to the sled db connection
  51. pub sled_db: sled::Db,
  52. /// Headers sled tree
  53. pub headers: HeaderStore,
  54. /// Blocks sled tree
  55. pub blocks: BlockStore,
  56. /// Transactions related sled trees
  57. pub transactions: TxStore,
  58. /// Contracts related sled trees
  59. pub contracts: ContractStore,
  60. }
  61. impl Blockchain {
  62. /// Instantiate a new `Blockchain` with the given `sled` database.
  63. pub fn new(db: &sled::Db) -> Result<Self> {
  64. let headers = HeaderStore::new(db)?;
  65. let blocks = BlockStore::new(db)?;
  66. let transactions = TxStore::new(db)?;
  67. let contracts = ContractStore::new(db)?;
  68. Ok(Self { sled_db: db.clone(), headers, blocks, transactions, contracts })
  69. }
  70. /// Insert a given [`BlockInfo`] into the blockchain database.
  71. /// This functions wraps all the logic of separating the block into specific
  72. /// data that can be fed into the different trees of the database.
  73. /// Upon success, the functions returns the block hash that
  74. /// were given and appended to the ledger.
  75. pub fn add_block(&self, block: &BlockInfo) -> Result<HeaderHash> {
  76. let mut trees = vec![];
  77. let mut batches = vec![];
  78. // Store header
  79. let (headers_batch, _) = self.headers.insert_batch(&[block.header.clone()]);
  80. trees.push(self.headers.main.clone());
  81. batches.push(headers_batch);
  82. // Store block
  83. let blk: Block = Block::from_block_info(block);
  84. let (bocks_batch, block_hashes) = self.blocks.insert_batch(&[blk]);
  85. let block_hash = block_hashes[0];
  86. let block_hash_vec = [block_hash];
  87. trees.push(self.blocks.main.clone());
  88. batches.push(bocks_batch);
  89. // Store block order
  90. let blocks_order_batch =
  91. self.blocks.insert_batch_order(&[block.header.height], &block_hash_vec);
  92. trees.push(self.blocks.order.clone());
  93. batches.push(blocks_order_batch);
  94. // Store transactions
  95. let (txs_batch, txs_hashes) = self.transactions.insert_batch(&block.txs);
  96. trees.push(self.transactions.main.clone());
  97. batches.push(txs_batch);
  98. // Store transactions_locations
  99. let txs_locations_batch =
  100. self.transactions.insert_batch_location(&txs_hashes, block.header.height);
  101. trees.push(self.transactions.location.clone());
  102. batches.push(txs_locations_batch);
  103. // Perform an atomic transaction over the trees and apply the batches.
  104. self.atomic_write(&trees, &batches)?;
  105. Ok(block_hash)
  106. }
  107. /// Check if the given [`BlockInfo`] is in the database and all trees.
  108. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  109. let blockhash = match self.blocks.get_order(&[block.header.height], true) {
  110. Ok(v) => v[0].unwrap(),
  111. Err(_) => return Ok(false),
  112. };
  113. // Check if we have all transactions
  114. let txs: Vec<TransactionHash> = block.txs.iter().map(|tx| tx.hash()).collect();
  115. if self.transactions.get(&txs, true).is_err() {
  116. return Ok(false)
  117. }
  118. // Check provided info produces the same hash
  119. Ok(blockhash == block.hash())
  120. }
  121. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  122. pub fn get_blocks_by_hash(&self, hashes: &[HeaderHash]) -> Result<Vec<BlockInfo>> {
  123. let blocks = self.blocks.get(hashes, true)?;
  124. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  125. let ret = self.get_blocks_infos(&blocks)?;
  126. Ok(ret)
  127. }
  128. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  129. /// Fails if any of them is not found
  130. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  131. let mut ret = Vec::with_capacity(blocks.len());
  132. for block in blocks {
  133. let headers = self.headers.get(&[block.header], true)?;
  134. // Since we used strict get, its safe to unwrap here
  135. let header = headers[0].clone().unwrap();
  136. let txs = self.transactions.get(&block.txs, true)?;
  137. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  138. let info = BlockInfo::new(header, txs, block.signature);
  139. ret.push(info);
  140. }
  141. Ok(ret)
  142. }
  143. /// Retrieve [`BlockInfo`]s by given heights. Does not fail if any of them are not found.
  144. pub fn get_blocks_by_heights(&self, heights: &[u32]) -> Result<Vec<BlockInfo>> {
  145. debug!(target: "blockchain", "get_blocks_by_heights(): {:?}", heights);
  146. let blockhashes = self.blocks.get_order(heights, false)?;
  147. let mut hashes = vec![];
  148. for i in blockhashes.into_iter().flatten() {
  149. hashes.push(i);
  150. }
  151. self.get_blocks_by_hash(&hashes)
  152. }
  153. /// Retrieve n headers before given block height.
  154. pub fn get_headers_before(&self, height: u32, n: usize) -> Result<Vec<Header>> {
  155. debug!(target: "blockchain", "get_headers_before(): {} -> {}", height, n);
  156. let hashes = self.blocks.get_before(height, n)?;
  157. let headers = self.headers.get(&hashes, true)?;
  158. Ok(headers.iter().map(|h| h.clone().unwrap()).collect())
  159. }
  160. /// Retrieve stored blocks count
  161. pub fn len(&self) -> usize {
  162. self.blocks.len()
  163. }
  164. /// Retrieve stored txs count
  165. pub fn txs_len(&self) -> usize {
  166. self.transactions.len()
  167. }
  168. /// Check if blockchain contains any blocks
  169. pub fn is_empty(&self) -> bool {
  170. self.blocks.is_empty()
  171. }
  172. /// Retrieve genesis (first) block height and hash.
  173. pub fn genesis(&self) -> Result<(u32, HeaderHash)> {
  174. self.blocks.get_first()
  175. }
  176. /// Retrieve genesis (first) block info.
  177. pub fn genesis_block(&self) -> Result<BlockInfo> {
  178. let (_, hash) = self.genesis()?;
  179. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  180. }
  181. /// Retrieve the last block height and hash.
  182. pub fn last(&self) -> Result<(u32, HeaderHash)> {
  183. self.blocks.get_last()
  184. }
  185. /// Retrieve the last block header.
  186. pub fn last_header(&self) -> Result<Header> {
  187. let (_, hash) = self.last()?;
  188. Ok(self.headers.get(&[hash], true)?[0].clone().unwrap())
  189. }
  190. /// Retrieve the last block info.
  191. pub fn last_block(&self) -> Result<BlockInfo> {
  192. let (_, hash) = self.last()?;
  193. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  194. }
  195. /// Retrieve the last block difficulty. If the tree is empty,
  196. /// returns `BlockDifficulty::genesis` difficulty.
  197. pub fn last_block_difficulty(&self) -> Result<BlockDifficulty> {
  198. if let Some(found) = self.blocks.get_last_difficulty()? {
  199. return Ok(found)
  200. }
  201. let genesis_block = self.genesis_block()?;
  202. Ok(BlockDifficulty::genesis(genesis_block.header.timestamp))
  203. }
  204. /// Check if block order for the given height is in the database.
  205. pub fn has_height(&self, height: u32) -> Result<bool> {
  206. let vec = match self.blocks.get_order(&[height], true) {
  207. Ok(v) => v,
  208. Err(_) => return Ok(false),
  209. };
  210. Ok(!vec.is_empty())
  211. }
  212. /// Insert a given slice of pending transactions into the blockchain database.
  213. /// On success, the function returns the transaction hashes in the same order
  214. /// as the input transactions.
  215. pub fn add_pending_txs(&self, txs: &[Transaction]) -> Result<Vec<TransactionHash>> {
  216. let (txs_batch, txs_hashes) = self.transactions.insert_batch_pending(txs);
  217. let txs_order_batch = self.transactions.insert_batch_pending_order(&txs_hashes)?;
  218. // Perform an atomic transaction over the trees and apply the batches.
  219. let trees = [self.transactions.pending.clone(), self.transactions.pending_order.clone()];
  220. let batches = [txs_batch, txs_order_batch];
  221. self.atomic_write(&trees, &batches)?;
  222. Ok(txs_hashes)
  223. }
  224. /// Retrieve all transactions from the pending tx store.
  225. /// Be careful as this will try to load everything in memory.
  226. pub fn get_pending_txs(&self) -> Result<Vec<Transaction>> {
  227. let txs = self.transactions.get_all_pending()?;
  228. let indexes = self.transactions.get_all_pending_order()?;
  229. if txs.len() != indexes.len() {
  230. return Err(Error::InvalidInputLengths)
  231. }
  232. let mut ret = Vec::with_capacity(txs.len());
  233. for index in indexes {
  234. ret.push(txs.get(&index.1).unwrap().clone());
  235. }
  236. Ok(ret)
  237. }
  238. /// Remove a given slice of pending transactions from the blockchain database.
  239. pub fn remove_pending_txs(&self, txs: &[Transaction]) -> Result<()> {
  240. let txs_hashes: Vec<TransactionHash> = txs.iter().map(|tx| tx.hash()).collect();
  241. self.remove_pending_txs_hashes(&txs_hashes)
  242. }
  243. /// Remove a given slice of pending transactions hashes from the blockchain database.
  244. pub fn remove_pending_txs_hashes(&self, txs: &[TransactionHash]) -> Result<()> {
  245. let indexes = self.transactions.get_all_pending_order()?;
  246. // We could do indexes.iter().map(|x| txs.contains(x.1)).collect.map(|x| x.0).collect
  247. // but this is faster since we don't do the second iteration
  248. let mut removed_indexes = vec![];
  249. for index in indexes {
  250. if txs.contains(&index.1) {
  251. removed_indexes.push(index.0);
  252. }
  253. }
  254. let txs_batch = self.transactions.remove_batch_pending(txs);
  255. let txs_order_batch = self.transactions.remove_batch_pending_order(&removed_indexes);
  256. // Perform an atomic transaction over the trees and apply the batches.
  257. let trees = [self.transactions.pending.clone(), self.transactions.pending_order.clone()];
  258. let batches = [txs_batch, txs_order_batch];
  259. self.atomic_write(&trees, &batches)?;
  260. Ok(())
  261. }
  262. /// Auxiliary function to write to multiple trees completely atomic.
  263. fn atomic_write(&self, trees: &[sled::Tree], batches: &[sled::Batch]) -> Result<()> {
  264. if trees.len() != batches.len() {
  265. return Err(Error::InvalidInputLengths)
  266. }
  267. trees.transaction(|trees| {
  268. for (index, tree) in trees.iter().enumerate() {
  269. tree.apply_batch(&batches[index])?;
  270. }
  271. Ok::<(), sled::transaction::ConflictableTransactionError<sled::Error>>(())
  272. })?;
  273. Ok(())
  274. }
  275. /// Retrieve all blocks contained in the blockchain in order.
  276. /// Be careful as this will try to load everything in memory.
  277. pub fn get_all(&self) -> Result<Vec<BlockInfo>> {
  278. let order = self.blocks.get_all_order()?;
  279. let order: Vec<HeaderHash> = order.iter().map(|x| x.1).collect();
  280. let blocks = self.get_blocks_by_hash(&order)?;
  281. Ok(blocks)
  282. }
  283. /// Retrieve [`BlockInfo`]s by given heights range.
  284. pub fn get_by_range(&self, start: u32, end: u32) -> Result<Vec<BlockInfo>> {
  285. let blockhashes = self.blocks.get_order_by_range(start, end)?;
  286. let hashes: Vec<HeaderHash> = blockhashes.into_iter().map(|(_, hash)| hash).collect();
  287. self.get_blocks_by_hash(&hashes)
  288. }
  289. /// Retrieve last 'N' [`BlockInfo`]s from the blockchain.
  290. pub fn get_last_n(&self, n: usize) -> Result<Vec<BlockInfo>> {
  291. let records = self.blocks.get_last_n_orders(n)?;
  292. let mut last_n = vec![];
  293. for record in records {
  294. let header_hash = record.1;
  295. let blocks = self.get_blocks_by_hash(&[header_hash])?;
  296. for block in blocks {
  297. last_n.push(block.clone());
  298. }
  299. }
  300. Ok(last_n)
  301. }
  302. /// Auxiliary function to reset the blockchain and consensus state
  303. /// to the provided block height.
  304. pub fn reset_to_height(&self, height: u32) -> Result<()> {
  305. // First we grab the last block height
  306. let (last, _) = self.last()?;
  307. // Check if request height is after our last height
  308. if height >= last {
  309. return Ok(())
  310. }
  311. // Grab all state inverse diffs until requested height,
  312. // going backwards.
  313. let heights: Vec<u32> = (height + 1..=last).rev().collect();
  314. let inverse_diffs = self.blocks.get_state_inverse_diff(&heights, true)?;
  315. // Create an overlay to apply the reverse diffs
  316. let overlay = BlockchainOverlay::new(self)?;
  317. // Apply the inverse diffs sequence
  318. let overlay_lock = overlay.lock().unwrap();
  319. let mut lock = overlay_lock.overlay.lock().unwrap();
  320. for inverse_diff in inverse_diffs {
  321. // Since we used strict retrieval it's safe to unwrap here
  322. let inverse_diff = inverse_diff.unwrap();
  323. lock.add_diff(&inverse_diff)?;
  324. lock.apply_diff(&inverse_diff)?;
  325. self.sled_db.flush()?;
  326. }
  327. drop(lock);
  328. drop(overlay_lock);
  329. Ok(())
  330. }
  331. /// Generate a Monotree(SMT) containing all contracts states
  332. /// checksums, along with the wasm bincodes checksum.
  333. ///
  334. /// Note: native contracts wasm bincodes are excluded.
  335. pub fn get_state_monotree(&self) -> Result<Monotree> {
  336. self.contracts.get_state_monotree(&self.sled_db)
  337. }
  338. }
  339. /// Atomic pointer to sled db overlay.
  340. pub type SledDbOverlayPtr = Arc<Mutex<sled_overlay::SledDbOverlay>>;
  341. /// Atomic pointer to blockchain overlay.
  342. pub type BlockchainOverlayPtr = Arc<Mutex<BlockchainOverlay>>;
  343. /// Overlay structure over a [`Blockchain`] instance.
  344. pub struct BlockchainOverlay {
  345. /// Main [`sled_overlay::SledDbOverlay`] to the sled db connection
  346. pub overlay: SledDbOverlayPtr,
  347. /// Headers overlay
  348. pub headers: HeaderStoreOverlay,
  349. /// Blocks overlay
  350. pub blocks: BlockStoreOverlay,
  351. /// Transactions overlay
  352. pub transactions: TxStoreOverlay,
  353. /// Contract overlay
  354. pub contracts: ContractStoreOverlay,
  355. }
  356. impl BlockchainOverlay {
  357. /// Instantiate a new `BlockchainOverlay` over the given [`Blockchain`] instance.
  358. pub fn new(blockchain: &Blockchain) -> Result<BlockchainOverlayPtr> {
  359. // Here we configure all our blockchain sled trees to be protected in the overlay
  360. let protected_trees = vec![
  361. SLED_BLOCK_TREE,
  362. SLED_BLOCK_ORDER_TREE,
  363. SLED_BLOCK_DIFFICULTY_TREE,
  364. SLED_BLOCK_STATE_INVERSE_DIFF_TREE,
  365. SLED_HEADER_TREE,
  366. SLED_SYNC_HEADER_TREE,
  367. SLED_TX_TREE,
  368. SLED_TX_LOCATION_TREE,
  369. SLED_PENDING_TX_TREE,
  370. SLED_PENDING_TX_ORDER_TREE,
  371. SLED_CONTRACTS_TREE,
  372. SLED_BINCODE_TREE,
  373. ];
  374. let overlay = Arc::new(Mutex::new(sled_overlay::SledDbOverlay::new(
  375. &blockchain.sled_db,
  376. protected_trees,
  377. )));
  378. let headers = HeaderStoreOverlay::new(&overlay)?;
  379. let blocks = BlockStoreOverlay::new(&overlay)?;
  380. let transactions = TxStoreOverlay::new(&overlay)?;
  381. let contracts = ContractStoreOverlay::new(&overlay)?;
  382. Ok(Arc::new(Mutex::new(Self { overlay, headers, blocks, transactions, contracts })))
  383. }
  384. /// Check if blockchain contains any blocks
  385. pub fn is_empty(&self) -> Result<bool> {
  386. self.blocks.is_empty()
  387. }
  388. /// Retrieve the last block height and hash.
  389. pub fn last(&self) -> Result<(u32, HeaderHash)> {
  390. self.blocks.get_last()
  391. }
  392. /// Retrieve the last block info.
  393. pub fn last_block(&self) -> Result<BlockInfo> {
  394. let (_, hash) = self.last()?;
  395. Ok(self.get_blocks_by_hash(&[hash])?[0].clone())
  396. }
  397. /// Retrieve the last block height.
  398. pub fn last_block_height(&self) -> Result<u32> {
  399. Ok(self.last()?.0)
  400. }
  401. /// Retrieve the last block timestamp.
  402. pub fn last_block_timestamp(&self) -> Result<Timestamp> {
  403. let (_, hash) = self.last()?;
  404. Ok(self.get_blocks_by_hash(&[hash])?[0].header.timestamp)
  405. }
  406. /// Insert a given [`BlockInfo`] into the overlay.
  407. /// This functions wraps all the logic of separating the block into specific
  408. /// data that can be fed into the different trees of the overlay.
  409. /// Upon success, the functions returns the block hash that
  410. /// were given and appended to the overlay.
  411. /// Since we are adding to the overlay, we don't need to exeucte
  412. /// the writes atomically.
  413. pub fn add_block(&self, block: &BlockInfo) -> Result<HeaderHash> {
  414. // Store header
  415. self.headers.insert(&[block.header.clone()])?;
  416. // Store block
  417. let blk: Block = Block::from_block_info(block);
  418. let txs_hashes = blk.txs.clone();
  419. let block_hash = self.blocks.insert(&[blk])?[0];
  420. let block_hash_vec = [block_hash];
  421. // Store block order
  422. self.blocks.insert_order(&[block.header.height], &block_hash_vec)?;
  423. // Store transactions
  424. self.transactions.insert(&block.txs)?;
  425. // Store transactions locations
  426. self.transactions.insert_location(&txs_hashes, block.header.height)?;
  427. Ok(block_hash)
  428. }
  429. /// Check if the given [`BlockInfo`] is in the database and all trees.
  430. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  431. let blockhash = match self.blocks.get_order(&[block.header.height], true) {
  432. Ok(v) => v[0].unwrap(),
  433. Err(_) => return Ok(false),
  434. };
  435. // Check if we have all transactions
  436. let txs: Vec<TransactionHash> = block.txs.iter().map(|tx| tx.hash()).collect();
  437. if self.transactions.get(&txs, true).is_err() {
  438. return Ok(false)
  439. }
  440. // Check provided info produces the same hash
  441. Ok(blockhash == block.hash())
  442. }
  443. /// Retrieve [`Header`]s by given hashes. Fails if any of them is not found.
  444. pub fn get_headers_by_hash(&self, hashes: &[HeaderHash]) -> Result<Vec<Header>> {
  445. let headers = self.headers.get(hashes, true)?;
  446. let ret: Vec<Header> = headers.iter().map(|x| x.clone().unwrap()).collect();
  447. Ok(ret)
  448. }
  449. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them is not found.
  450. pub fn get_blocks_by_hash(&self, hashes: &[HeaderHash]) -> Result<Vec<BlockInfo>> {
  451. let blocks = self.blocks.get(hashes, true)?;
  452. let blocks: Vec<Block> = blocks.iter().map(|x| x.clone().unwrap()).collect();
  453. let ret = self.get_blocks_infos(&blocks)?;
  454. Ok(ret)
  455. }
  456. /// Retrieve all [`BlockInfo`] for given slice of [`Block`].
  457. /// Fails if any of them is not found
  458. fn get_blocks_infos(&self, blocks: &[Block]) -> Result<Vec<BlockInfo>> {
  459. let mut ret = Vec::with_capacity(blocks.len());
  460. for block in blocks {
  461. let headers = self.headers.get(&[block.header], true)?;
  462. // Since we used strict get, its safe to unwrap here
  463. let header = headers[0].clone().unwrap();
  464. let txs = self.transactions.get(&block.txs, true)?;
  465. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  466. let info = BlockInfo::new(header, txs, block.signature);
  467. ret.push(info);
  468. }
  469. Ok(ret)
  470. }
  471. /// Retrieve [`Block`]s by given hashes and return their transactions hashes.
  472. pub fn get_blocks_txs_hashes(&self, hashes: &[HeaderHash]) -> Result<Vec<TransactionHash>> {
  473. let blocks = self.blocks.get(hashes, true)?;
  474. let mut ret = vec![];
  475. for block in blocks {
  476. ret.extend_from_slice(&block.unwrap().txs);
  477. }
  478. Ok(ret)
  479. }
  480. /// Checkpoint overlay so we can revert to it, if needed.
  481. pub fn checkpoint(&self) {
  482. self.overlay.lock().unwrap().checkpoint();
  483. }
  484. /// Revert to current overlay checkpoint.
  485. pub fn revert_to_checkpoint(&self) -> Result<()> {
  486. self.overlay.lock().unwrap().revert_to_checkpoint()?;
  487. Ok(())
  488. }
  489. /// Auxiliary function to create a full clone using SledDbOverlay::clone,
  490. /// generating new pointers for the underlying overlays.
  491. pub fn full_clone(&self) -> Result<BlockchainOverlayPtr> {
  492. let overlay = Arc::new(Mutex::new(self.overlay.lock().unwrap().clone()));
  493. let headers = HeaderStoreOverlay::new(&overlay)?;
  494. let blocks = BlockStoreOverlay::new(&overlay)?;
  495. let transactions = TxStoreOverlay::new(&overlay)?;
  496. let contracts = ContractStoreOverlay::new(&overlay)?;
  497. Ok(Arc::new(Mutex::new(Self { overlay, headers, blocks, transactions, contracts })))
  498. }
  499. /// Generate a Monotree(SMT) containing all contracts states
  500. /// checksums, along with the wasm bincodes checksum.
  501. /// A clone is used so we are not affected by the opened trees
  502. /// during checksum computing.
  503. ///
  504. /// Note: native contracts wasm bincodes are excluded.
  505. pub fn get_state_monotree(&self) -> Result<Monotree> {
  506. self.full_clone()?.lock().unwrap().contracts.get_state_monotree()
  507. }
  508. }