mod.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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 darkfi_serial::serialize;
  19. use log::debug;
  20. use crate::{
  21. consensus::{Block, BlockInfo},
  22. util::time::Timestamp,
  23. Result,
  24. };
  25. pub mod blockstore;
  26. pub use blockstore::{BlockOrderStore, BlockStore, HeaderStore};
  27. pub mod nfstore;
  28. pub use nfstore::NullifierStore;
  29. pub mod rootstore;
  30. pub use rootstore::RootStore;
  31. pub mod txstore;
  32. pub use txstore::TxStore;
  33. pub mod contractstore;
  34. pub use contractstore::ContractStore;
  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. /// Block order sled tree
  45. pub order: BlockOrderStore,
  46. /// Transactions sled tree
  47. pub transactions: TxStore,
  48. /// Nullifiers sled tree
  49. pub nullifiers: NullifierStore,
  50. /// Merkle roots sled tree
  51. pub merkle_roots: RootStore,
  52. /// Contract states
  53. pub contracts: ContractStore,
  54. }
  55. impl Blockchain {
  56. //FIXME why the blockchain taking genesis_data on the constructor as a hash?
  57. //genesis data are supposed to be a a hash?
  58. /// Instantiate a new `Blockchain` with the given `sled` database.
  59. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  60. let headers = HeaderStore::new(db, genesis_ts, genesis_data)?;
  61. let blocks = BlockStore::new(db, genesis_ts, genesis_data)?;
  62. let order = BlockOrderStore::new(db, genesis_ts, genesis_data)?;
  63. let transactions = TxStore::new(db)?;
  64. let nullifiers = NullifierStore::new(db)?;
  65. let merkle_roots = RootStore::new(db)?;
  66. let contracts = ContractStore::new(db)?;
  67. Ok(Self {
  68. sled_db: db.clone(),
  69. headers,
  70. blocks,
  71. order,
  72. transactions,
  73. nullifiers,
  74. merkle_roots,
  75. contracts,
  76. })
  77. }
  78. /// Insert a given slice of [`BlockInfo`] into the blockchain database.
  79. /// This functions wraps all the logic of separating the block into specific
  80. /// data that can be fed into the different trees of the database.
  81. /// Upon success, the functions returns a vector of the block hashes that
  82. /// were given and appended to the ledger.
  83. pub fn add(&self, blocks: &[BlockInfo]) -> Result<Vec<blake3::Hash>> {
  84. let mut ret = Vec::with_capacity(blocks.len());
  85. for block in blocks {
  86. // Store transactions
  87. let _tx_hashes = self.transactions.insert(&block.txs)?;
  88. // Store header
  89. let headerhash = self.headers.insert(&[block.header.clone()])?;
  90. ret.push(headerhash[0]);
  91. // Store block
  92. //let _block = Block::new(headerhash[0], tx_hashes, block.m.clone());
  93. //self.blocks.insert(&[_block])?;
  94. let blk: Block = Block::from(block.clone());
  95. self.blocks.insert(&[blk])?;
  96. // Store block order
  97. self.order.insert(&[block.header.slot], &[headerhash[0]])?;
  98. // NOTE: The nullifiers and Merkle roots are applied in the state
  99. // transition apply function.
  100. }
  101. Ok(ret)
  102. }
  103. /// Check if the given [`BlockInfo`] is in the database and all trees.
  104. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  105. let blockhash = match self.order.get(&[block.header.slot], true) {
  106. Ok(v) => v[0].unwrap(),
  107. Err(_) => return Ok(false),
  108. };
  109. // TODO: Check if we have all transactions
  110. // Check provided info produces the same hash
  111. Ok(blockhash == block.header.headerhash())
  112. }
  113. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them are not found.
  114. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  115. let mut ret = Vec::with_capacity(hashes.len());
  116. let headers = self.headers.get(hashes, true)?;
  117. let blocks = self.blocks.get(hashes, true)?;
  118. for (i, header) in headers.iter().enumerate() {
  119. let header = header.clone().unwrap();
  120. let block = blocks[i].clone().unwrap();
  121. let txs = self.transactions.get(&block.txs, true)?;
  122. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  123. let info = BlockInfo::new(header, txs, block.metadata.clone());
  124. ret.push(info);
  125. }
  126. Ok(ret)
  127. }
  128. /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
  129. pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
  130. debug!("get_blocks_by_slot(): {:?}", slots);
  131. let blockhashes = self.order.get(slots, false)?;
  132. let mut hashes = vec![];
  133. for i in blockhashes.into_iter().flatten() {
  134. hashes.push(i);
  135. }
  136. self.get_blocks_by_hash(&hashes)
  137. }
  138. /// Retrieve n blocks after given start slot.
  139. pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
  140. debug!("get_blocks_after(): {} -> {}", slot, n);
  141. let hashes = self.order.get_after(slot, n)?;
  142. self.get_blocks_by_hash(&hashes)
  143. }
  144. /// Retrieve the last block slot and hash.
  145. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  146. self.order.get_last()
  147. }
  148. /// Retrieve last finalized block leader proof hash.
  149. pub fn get_last_proof_hash(&self) -> Result<blake3::Hash> {
  150. let (slot, _) = self.last().unwrap();
  151. let block = &self.get_blocks_by_slot(&vec![slot]).unwrap()[0];
  152. let hash = blake3::hash(&serialize(&block.metadata.proof));
  153. Ok(hash)
  154. }
  155. }