zebra_state/service/non_finalized_state/
backup.rs1use std::{
2 collections::{BTreeMap, HashMap, HashSet},
3 fs::DirEntry,
4 io::{self, ErrorKind},
5 path::{Path, PathBuf},
6 sync::Arc,
7 time::{Duration, Instant},
8};
9
10use hex::ToHex;
11use zebra_chain::{
12 amount::Amount,
13 block::{self, Block, Height},
14 serialization::{ZcashDeserializeInto, ZcashSerialize},
15};
16
17use crate::{
18 ContextuallyVerifiedBlock, IntoDisk, NonFinalizedState, SemanticallyVerifiedBlock,
19 WatchReceiver, ZebraDb,
20};
21
22#[cfg(not(test))]
23use crate::service::write::validate_and_commit_non_finalized;
24
25pub(crate) const MIN_DURATION_BETWEEN_BACKUP_UPDATES: Duration = Duration::from_secs(5);
27
28pub(super) fn restore_backup(
35 mut non_finalized_state: NonFinalizedState,
36 backup_dir_path: &Path,
37 finalized_state: &ZebraDb,
38) -> NonFinalizedState {
39 let started = Instant::now();
40 let mut restored_blocks: usize = 0;
41 let mut store: BTreeMap<Height, Vec<SemanticallyVerifiedBlock>> = BTreeMap::new();
42
43 for block in read_non_finalized_blocks_from_backup(backup_dir_path, finalized_state) {
44 store.entry(block.height).or_default().push(block);
45 }
46
47 'restore: for (height, blocks) in store {
48 for block in blocks {
49 if non_finalized_state.should_finalize_root() {
53 tracing::warn!(
54 ?height,
55 "the non-finalized backup is over the non-finalized state limits: \
56 not restoring its remaining blocks"
57 );
58 break 'restore;
59 }
60
61 #[cfg(test)]
62 let commit_result = if non_finalized_state
63 .any_chain_contains(&block.block.header.previous_block_hash)
64 {
65 non_finalized_state.commit_block(block, finalized_state)
66 } else {
67 non_finalized_state.commit_new_chain(block, finalized_state)
68 };
69
70 #[cfg(not(test))]
71 let commit_result =
72 validate_and_commit_non_finalized(finalized_state, &mut non_finalized_state, block);
73
74 if let Err(commit_error) = commit_result {
76 tracing::warn!(
77 ?commit_error,
78 ?height,
79 "failed to commit non-finalized block from backup directory"
80 );
81 } else {
82 restored_blocks += 1;
83 }
84 }
85 }
86
87 metrics::gauge!("state.memory.backup.restored.block.count").set(restored_blocks as f64);
89 metrics::gauge!("state.memory.backup.restore.duration_seconds")
90 .set(started.elapsed().as_secs_f64());
91
92 non_finalized_state
93}
94
95pub(super) fn update_non_finalized_state_backup(
105 backup_dir_path: &Path,
106 non_finalized_state: &NonFinalizedState,
107 mut backup_blocks: HashMap<block::Hash, PathBuf>,
108) {
109 let mut seen = HashSet::new();
110 for block in non_finalized_state
111 .chain_iter()
112 .flat_map(|chain| chain.blocks.values())
113 .filter(|block| seen.insert(block.hash))
115 .filter(|block| backup_blocks.remove(&block.hash).is_none())
117 {
118 write_backup_block(backup_dir_path, block);
121 }
122
123 for (_, outdated_backup_block_path) in backup_blocks {
125 if let Err(delete_error) = std::fs::remove_file(outdated_backup_block_path) {
126 tracing::warn!(?delete_error, "failed to delete backup block file");
127 }
128 }
129}
130
131pub(super) async fn run_backup_task(
135 mut non_finalized_state_receiver: WatchReceiver<NonFinalizedState>,
136 backup_dir_path: PathBuf,
137) {
138 let err = loop {
139 let rate_limit = tokio::time::sleep(MIN_DURATION_BETWEEN_BACKUP_UPDATES);
140 let backup_blocks: HashMap<block::Hash, PathBuf> = {
141 let backup_dir_path = backup_dir_path.clone();
142 tokio::task::spawn_blocking(move || list_backup_dir_entries(&backup_dir_path))
143 .await
144 .expect("failed to join blocking task when reading in backup task")
145 .collect()
146 };
147
148 if let (Err(err), _) = tokio::join!(non_finalized_state_receiver.changed(), rate_limit) {
149 break err;
150 };
151
152 let latest_non_finalized_state = non_finalized_state_receiver.cloned_watch_data();
153
154 let backup_dir_path = backup_dir_path.clone();
155 tokio::task::spawn_blocking(move || {
156 update_non_finalized_state_backup(
157 &backup_dir_path,
158 &latest_non_finalized_state,
159 backup_blocks,
160 );
161 })
162 .await
163 .expect("failed to join blocking task when writing in backup task");
164 };
165
166 tracing::warn!(
167 ?err,
168 "got recv error waiting on non-finalized state change, is Zebra shutting down?"
169 )
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173struct NonFinalizedBlockBackup {
174 block: Arc<Block>,
175 deferred_pool_balance_change: Amount,
176}
177
178impl From<&ContextuallyVerifiedBlock> for NonFinalizedBlockBackup {
179 fn from(cv_block: &ContextuallyVerifiedBlock) -> Self {
180 Self {
181 block: cv_block.block.clone(),
182 deferred_pool_balance_change: cv_block.chain_value_pool_change.deferred_amount(),
183 }
184 }
185}
186
187impl NonFinalizedBlockBackup {
188 fn as_bytes(&self) -> Vec<u8> {
190 let block_bytes = self
191 .block
192 .zcash_serialize_to_vec()
193 .expect("verified block header version should be valid");
194
195 let deferred_pool_balance_change_bytes =
196 self.deferred_pool_balance_change.as_bytes().to_vec();
197
198 [deferred_pool_balance_change_bytes, block_bytes].concat()
199 }
200
201 #[allow(clippy::unwrap_in_result)]
203 fn from_bytes(bytes: Vec<u8>) -> Result<Self, io::Error> {
204 let (deferred_pool_balance_change_bytes, block_bytes) = bytes
205 .split_at_checked(size_of::<Amount>())
206 .ok_or(io::Error::new(
207 ErrorKind::InvalidInput,
208 "input is too short",
209 ))?;
210
211 Ok(Self {
212 block: Arc::new(
213 block_bytes
214 .zcash_deserialize_into()
215 .map_err(|err| io::Error::new(ErrorKind::InvalidData, err))?,
216 ),
217 deferred_pool_balance_change: Amount::from_bytes(
218 deferred_pool_balance_change_bytes
219 .try_into()
220 .expect("slice from `split_at_checked()` should fit in [u8; 8]"),
221 )
222 .map_err(|err| io::Error::new(ErrorKind::InvalidData, err))?,
223 })
224 }
225}
226
227fn write_backup_block(backup_dir_path: &Path, block: &ContextuallyVerifiedBlock) {
229 let backup_block_file_name: String = block.hash.encode_hex();
230 let backup_block_file_path = backup_dir_path.join(backup_block_file_name);
231 let non_finalized_block_backup: NonFinalizedBlockBackup = block.into();
232
233 if let Err(err) = std::fs::write(
234 backup_block_file_path,
235 non_finalized_block_backup.as_bytes(),
236 ) {
237 tracing::warn!(?err, "failed to write non-finalized state backup block");
238 }
239}
240
241fn read_non_finalized_blocks_from_backup<'a>(
245 backup_dir_path: &Path,
246 finalized_state: &'a ZebraDb,
247) -> impl Iterator<Item = SemanticallyVerifiedBlock> + 'a {
248 list_backup_dir_entries(backup_dir_path)
249 .filter(|&(block_hash, _)| !finalized_state.contains_hash(block_hash))
252 .filter_map(|(block_hash, file_path)| match std::fs::read(file_path) {
253 Ok(block_bytes) => Some((block_hash, block_bytes)),
254 Err(err) => {
255 tracing::warn!(?err, "failed to open non-finalized state backup block file");
256 None
257 }
258 })
259 .filter_map(|(expected_block_hash, backup_block_file_contents)| {
260 match NonFinalizedBlockBackup::from_bytes(backup_block_file_contents) {
261 Ok(NonFinalizedBlockBackup {
262 block,
263 deferred_pool_balance_change: _,
264 }) if block.coinbase_height().is_some() => {
265 let block = SemanticallyVerifiedBlock::from(block);
266 if block.hash != expected_block_hash {
267 tracing::warn!(
268 block_hash = ?block.hash,
269 ?expected_block_hash,
270 "wrong block hash in file name"
271 );
272 }
273 Some(block)
274 }
275 Ok(block) => {
276 tracing::warn!(
277 ?block,
278 "invalid non-finalized backup block, missing coinbase height"
279 );
280 None
281 }
282 Err(err) => {
283 tracing::warn!(
284 ?err,
285 "failed to deserialize non-finalized backup data into block"
286 );
287 None
288 }
289 }
290 })
291}
292
293pub(super) fn list_backup_dir_entries(
301 backup_dir_path: &Path,
302) -> impl Iterator<Item = (block::Hash, PathBuf)> {
303 read_backup_dir(backup_dir_path).filter_map(process_backup_dir_entry)
304}
305
306fn read_backup_dir(backup_dir_path: &Path) -> impl Iterator<Item = DirEntry> {
314 std::fs::read_dir(backup_dir_path)
315 .expect("failed to read non-finalized state backup directory")
316 .filter_map(|entry| match entry {
317 Ok(entry) => Some(entry),
318 Err(io_err) => {
319 tracing::warn!(
320 ?io_err,
321 "failed to read DirEntry in non-finalized state backup dir"
322 );
323
324 None
325 }
326 })
327}
328
329fn process_backup_dir_entry(entry: DirEntry) -> Option<(block::Hash, PathBuf)> {
335 let delete_file = || {
336 if let Err(delete_error) = std::fs::remove_file(entry.path()) {
337 tracing::warn!(?delete_error, "failed to delete backup block file");
338 }
339 };
340
341 let block_file_name = match entry.file_name().into_string() {
342 Ok(block_hash) => block_hash,
343 Err(err) => {
344 tracing::warn!(
345 ?err,
346 "failed to convert OsString to String, attempting to delete file"
347 );
348
349 delete_file();
350 return None;
351 }
352 };
353
354 let block_hash: block::Hash = match block_file_name.parse() {
355 Ok(block_hash) => block_hash,
356 Err(err) => {
357 tracing::warn!(
358 ?err,
359 "failed to parse hex-encoded block hash from file name, attempting to delete file"
360 );
361
362 delete_file();
363 return None;
364 }
365 };
366
367 Some((block_hash, entry.path()))
368}