mod.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. use std::io;
  2. use log::debug;
  3. use crate::{
  4. consensus::{Block, BlockInfo},
  5. impl_vec,
  6. util::{
  7. serial::{Decodable, Encodable, ReadExt, VarInt, WriteExt},
  8. time::Timestamp,
  9. },
  10. Result,
  11. };
  12. pub mod blockstore;
  13. pub use blockstore::{BlockOrderStore, BlockStore, HeaderStore};
  14. pub mod metadatastore;
  15. pub use metadatastore::StreamletMetadataStore;
  16. pub mod nfstore;
  17. pub use nfstore::NullifierStore;
  18. pub mod rootstore;
  19. pub use rootstore::RootStore;
  20. pub mod txstore;
  21. pub use txstore::TxStore;
  22. /// Structure holding all sled trees that comprise the concept of Blockchain.
  23. pub struct Blockchain {
  24. /// Headers sled tree
  25. pub headers: HeaderStore,
  26. /// Blocks sled tree
  27. pub blocks: BlockStore,
  28. /// Block order sled tree
  29. pub order: BlockOrderStore,
  30. /// Transactions sled tree
  31. pub transactions: TxStore,
  32. /// Streamlet metadata sled tree
  33. pub streamlet_metadata: StreamletMetadataStore,
  34. /// Nullifiers sled tree
  35. pub nullifiers: NullifierStore,
  36. /// Merkle roots sled tree
  37. pub merkle_roots: RootStore,
  38. }
  39. impl Blockchain {
  40. /// Instantiate a new `Blockchain` with the given `sled` database.
  41. pub fn new(db: &sled::Db, genesis_ts: Timestamp, genesis_data: blake3::Hash) -> Result<Self> {
  42. let headers = HeaderStore::new(db, genesis_ts, genesis_data)?;
  43. let blocks = BlockStore::new(db, genesis_ts, genesis_data)?;
  44. let order = BlockOrderStore::new(db, genesis_ts, genesis_data)?;
  45. let streamlet_metadata = StreamletMetadataStore::new(db, genesis_ts, genesis_data)?;
  46. let transactions = TxStore::new(db)?;
  47. let nullifiers = NullifierStore::new(db)?;
  48. let merkle_roots = RootStore::new(db)?;
  49. Ok(Self {
  50. headers,
  51. blocks,
  52. order,
  53. transactions,
  54. streamlet_metadata,
  55. nullifiers,
  56. merkle_roots,
  57. })
  58. }
  59. /// Insert a given slice of [`BlockInfo`] into the blockchain database.
  60. /// This functions wraps all the logic of separating the block into specific
  61. /// data that can be fed into the different trees of the database.
  62. /// Upon success, the functions returns a vector of the block hashes that
  63. /// were given and appended to the ledger.
  64. pub fn add(&self, blocks: &[BlockInfo]) -> Result<Vec<blake3::Hash>> {
  65. let mut ret = Vec::with_capacity(blocks.len());
  66. for block in blocks {
  67. // Store transactions
  68. let tx_hashes = self.transactions.insert(&block.txs)?;
  69. // Store header
  70. let headerhash = self.headers.insert(&[block.header.clone()])?;
  71. ret.push(headerhash[0]);
  72. // Store block
  73. let _block = Block::new(headerhash[0], tx_hashes, block.metadata.clone());
  74. self.blocks.insert(&[_block])?;
  75. // Store block order
  76. self.order.insert(&[block.header.slot], &[headerhash[0]])?;
  77. // Store streamlet metadata
  78. self.streamlet_metadata.insert(&[headerhash[0]], &[block.sm.clone()])?;
  79. // NOTE: The nullifiers and Merkle roots are applied in the state
  80. // transition apply function.
  81. }
  82. Ok(ret)
  83. }
  84. /// Check if the given [`BlockInfo`] is in the database and all trees.
  85. pub fn has_block(&self, block: &BlockInfo) -> Result<bool> {
  86. let blockhash = match self.order.get(&[block.header.slot], true) {
  87. Ok(v) => v[0].unwrap(),
  88. Err(_) => return Ok(false),
  89. };
  90. // TODO: Check if we have all transactions
  91. // Check provided info produces the same hash
  92. Ok(blockhash == block.header.headerhash())
  93. }
  94. /// Retrieve [`BlockInfo`]s by given hashes. Fails if any of them are not found.
  95. pub fn get_blocks_by_hash(&self, hashes: &[blake3::Hash]) -> Result<Vec<BlockInfo>> {
  96. let mut ret = Vec::with_capacity(hashes.len());
  97. let headers = self.headers.get(hashes, true)?;
  98. let blocks = self.blocks.get(hashes, true)?;
  99. let metadata = self.streamlet_metadata.get(hashes, true)?;
  100. for (i, header) in headers.iter().enumerate() {
  101. let header = header.clone().unwrap();
  102. let block = blocks[i].clone().unwrap();
  103. let sm = metadata[i].clone().unwrap();
  104. let txs = self.transactions.get(&block.txs, true)?;
  105. let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
  106. let info = BlockInfo::new(header, txs, block.metadata.clone(), sm);
  107. ret.push(info);
  108. }
  109. Ok(ret)
  110. }
  111. /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
  112. pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
  113. debug!("get_blocks_by_slot(): {:?}", slots);
  114. let blockhashes = self.order.get(slots, false)?;
  115. let mut hashes = vec![];
  116. for i in blockhashes.into_iter().flatten() {
  117. hashes.push(i);
  118. }
  119. self.get_blocks_by_hash(&hashes)
  120. }
  121. /// Retrieve n blocks after given start slot.
  122. pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
  123. debug!("get_blocks_after(): {} -> {}", slot, n);
  124. let hashes = self.order.get_after(slot, n)?;
  125. self.get_blocks_by_hash(&hashes)
  126. }
  127. /// Retrieve the last block slot and hash.
  128. pub fn last(&self) -> Result<(u64, blake3::Hash)> {
  129. self.order.get_last()
  130. }
  131. }
  132. impl Encodable for blake3::Hash {
  133. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  134. s.write_slice(self.as_bytes())?;
  135. Ok(32)
  136. }
  137. }
  138. impl Decodable for blake3::Hash {
  139. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  140. let mut bytes = [0u8; 32];
  141. d.read_slice(&mut bytes)?;
  142. Ok(bytes.into())
  143. }
  144. }
  145. impl_vec!(blake3::Hash);