mod.rs 5.3 KB

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