mod.rs 6.1 KB

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