mod.rs 22 KB

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