mod.rs 5.3 KB

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