|
| 1 | +//! Header storage operations for DiskStorageManager. |
| 2 | +
|
| 3 | +use std::collections::HashMap; |
| 4 | +use std::ops::Range; |
| 5 | +use std::path::PathBuf; |
| 6 | + |
| 7 | +use async_trait::async_trait; |
| 8 | +use dashcore::block::Header as BlockHeader; |
| 9 | +use dashcore::BlockHash; |
| 10 | +use tokio::sync::RwLock; |
| 11 | + |
| 12 | +use crate::error::StorageResult; |
| 13 | +use crate::storage::io::atomic_write; |
| 14 | +use crate::storage::segments::SegmentCache; |
| 15 | +use crate::storage::PersistentStorage; |
| 16 | +use crate::StorageError; |
| 17 | + |
| 18 | +#[async_trait] |
| 19 | +pub trait BlockHeaderStorage { |
| 20 | + async fn store_headers(&mut self, headers: &[BlockHeader]) -> StorageResult<()>; |
| 21 | + |
| 22 | + async fn store_headers_at_height( |
| 23 | + &mut self, |
| 24 | + headers: &[BlockHeader], |
| 25 | + height: u32, |
| 26 | + ) -> StorageResult<()>; |
| 27 | + |
| 28 | + async fn load_headers(&self, range: Range<u32>) -> StorageResult<Vec<BlockHeader>>; |
| 29 | + |
| 30 | + async fn get_header(&self, height: u32) -> StorageResult<Option<BlockHeader>> { |
| 31 | + if let Some(tip_height) = self.get_tip_height().await { |
| 32 | + if height > tip_height { |
| 33 | + return Ok(None); |
| 34 | + } |
| 35 | + } else { |
| 36 | + return Ok(None); |
| 37 | + } |
| 38 | + |
| 39 | + if let Some(start_height) = self.get_start_height().await { |
| 40 | + if height < start_height { |
| 41 | + return Ok(None); |
| 42 | + } |
| 43 | + } else { |
| 44 | + return Ok(None); |
| 45 | + } |
| 46 | + |
| 47 | + Ok(self.load_headers(height..height + 1).await?.first().copied()) |
| 48 | + } |
| 49 | + |
| 50 | + async fn get_tip_height(&self) -> Option<u32>; |
| 51 | + |
| 52 | + async fn get_start_height(&self) -> Option<u32>; |
| 53 | + |
| 54 | + async fn get_stored_headers_len(&self) -> u32; |
| 55 | + |
| 56 | + async fn get_header_height_by_hash( |
| 57 | + &self, |
| 58 | + hash: &dashcore::BlockHash, |
| 59 | + ) -> StorageResult<Option<u32>>; |
| 60 | +} |
| 61 | + |
| 62 | +pub struct PersistentBlockHeaderStorage { |
| 63 | + block_headers: RwLock<SegmentCache<BlockHeader>>, |
| 64 | + header_hash_index: HashMap<BlockHash, u32>, |
| 65 | +} |
| 66 | + |
| 67 | +impl PersistentBlockHeaderStorage { |
| 68 | + const FOLDER_NAME: &str = "block_headers"; |
| 69 | + const INDEX_FILE_NAME: &str = "index.dat"; |
| 70 | +} |
| 71 | + |
| 72 | +#[async_trait] |
| 73 | +impl PersistentStorage for PersistentBlockHeaderStorage { |
| 74 | + async fn open(storage_path: impl Into<PathBuf> + Send) -> StorageResult<Self> { |
| 75 | + let storage_path = storage_path.into(); |
| 76 | + let segments_folder = storage_path.join(Self::FOLDER_NAME); |
| 77 | + |
| 78 | + let index_path = segments_folder.join(Self::INDEX_FILE_NAME); |
| 79 | + |
| 80 | + let mut block_headers = SegmentCache::load_or_new(&segments_folder).await?; |
| 81 | + |
| 82 | + let header_hash_index = match tokio::fs::read(&index_path) |
| 83 | + .await |
| 84 | + .ok() |
| 85 | + .and_then(|content| bincode::deserialize(&content).ok()) |
| 86 | + { |
| 87 | + Some(index) => index, |
| 88 | + _ => { |
| 89 | + if segments_folder.exists() { |
| 90 | + block_headers.build_block_index_from_segments().await? |
| 91 | + } else { |
| 92 | + HashMap::new() |
| 93 | + } |
| 94 | + } |
| 95 | + }; |
| 96 | + |
| 97 | + Ok(Self { |
| 98 | + block_headers: RwLock::new(block_headers), |
| 99 | + header_hash_index, |
| 100 | + }) |
| 101 | + } |
| 102 | + |
| 103 | + async fn persist(&mut self, storage_path: impl Into<PathBuf> + Send) -> StorageResult<()> { |
| 104 | + let block_headers_folder = storage_path.into().join(Self::FOLDER_NAME); |
| 105 | + let index_path = block_headers_folder.join(Self::INDEX_FILE_NAME); |
| 106 | + |
| 107 | + tokio::fs::create_dir_all(&block_headers_folder).await?; |
| 108 | + |
| 109 | + self.block_headers.write().await.persist(&block_headers_folder).await; |
| 110 | + |
| 111 | + let data = bincode::serialize(&self.header_hash_index) |
| 112 | + .map_err(|e| StorageError::WriteFailed(format!("Failed to serialize index: {}", e)))?; |
| 113 | + |
| 114 | + atomic_write(&index_path, &data).await |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +#[async_trait] |
| 119 | +impl BlockHeaderStorage for PersistentBlockHeaderStorage { |
| 120 | + async fn store_headers(&mut self, headers: &[BlockHeader]) -> StorageResult<()> { |
| 121 | + let height = self.block_headers.read().await.next_height(); |
| 122 | + self.store_headers_at_height(headers, height).await |
| 123 | + } |
| 124 | + |
| 125 | + async fn store_headers_at_height( |
| 126 | + &mut self, |
| 127 | + headers: &[BlockHeader], |
| 128 | + height: u32, |
| 129 | + ) -> StorageResult<()> { |
| 130 | + let mut height = height; |
| 131 | + |
| 132 | + let hashes = headers.iter().map(|header| header.block_hash()).collect::<Vec<_>>(); |
| 133 | + |
| 134 | + self.block_headers.write().await.store_items_at_height(headers, height).await?; |
| 135 | + |
| 136 | + for hash in hashes { |
| 137 | + self.header_hash_index.insert(hash, height); |
| 138 | + height += 1; |
| 139 | + } |
| 140 | + |
| 141 | + Ok(()) |
| 142 | + } |
| 143 | + |
| 144 | + async fn load_headers(&self, range: Range<u32>) -> StorageResult<Vec<BlockHeader>> { |
| 145 | + self.block_headers.write().await.get_items(range).await |
| 146 | + } |
| 147 | + |
| 148 | + async fn get_tip_height(&self) -> Option<u32> { |
| 149 | + self.block_headers.read().await.tip_height() |
| 150 | + } |
| 151 | + |
| 152 | + async fn get_start_height(&self) -> Option<u32> { |
| 153 | + self.block_headers.read().await.start_height() |
| 154 | + } |
| 155 | + |
| 156 | + async fn get_stored_headers_len(&self) -> u32 { |
| 157 | + let block_headers = self.block_headers.read().await; |
| 158 | + |
| 159 | + let start_height = if let Some(start_height) = block_headers.start_height() { |
| 160 | + start_height |
| 161 | + } else { |
| 162 | + return 0; |
| 163 | + }; |
| 164 | + |
| 165 | + let end_height = if let Some(end_height) = block_headers.tip_height() { |
| 166 | + end_height |
| 167 | + } else { |
| 168 | + return 0; |
| 169 | + }; |
| 170 | + |
| 171 | + end_height - start_height + 1 |
| 172 | + } |
| 173 | + |
| 174 | + async fn get_header_height_by_hash( |
| 175 | + &self, |
| 176 | + hash: &dashcore::BlockHash, |
| 177 | + ) -> StorageResult<Option<u32>> { |
| 178 | + Ok(self.header_hash_index.get(hash).copied()) |
| 179 | + } |
| 180 | +} |
0 commit comments