zebra_state/config.rs
1//! Cached state configuration for Zebra.
2
3use std::{
4 fs::{self, canonicalize, remove_dir_all, DirEntry, ReadDir},
5 io::ErrorKind,
6 path::{Path, PathBuf},
7 time::Duration,
8};
9
10use semver::Version;
11use serde::{Deserialize, Serialize};
12use tokio::task::{spawn_blocking, JoinHandle};
13use tracing::Span;
14
15use zebra_chain::{common::default_cache_dir, parameters::Network};
16
17use crate::{
18 constants::{DATABASE_FORMAT_VERSION_FILE_NAME, STATE_DATABASE_KIND},
19 service::finalized_state::restorable_db_versions,
20 state_database_format_version_in_code, BoxError,
21};
22
23/// Configuration for the state service.
24#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
25#[serde(deny_unknown_fields, default)]
26pub struct Config {
27 /// The root directory for storing cached block data.
28 ///
29 /// If you change this directory, you might also want to change `network.cache_dir`.
30 ///
31 /// This cache stores permanent blockchain state that can be replicated from
32 /// the network, including the best chain, blocks, the UTXO set, and other indexes.
33 /// Any state that can be rolled back is only stored in memory.
34 ///
35 /// The `zebra-state` cache does *not* include any private data, such as wallet data.
36 ///
37 /// You can delete the entire cached state directory, but it will impact your node's
38 /// readiness and network usage. If you do, Zebra will re-sync from genesis the next
39 /// time it is launched.
40 ///
41 /// The default directory is platform dependent, based on
42 /// [`dirs::cache_dir()`](https://docs.rs/dirs/3.0.1/dirs/fn.cache_dir.html):
43 ///
44 /// |Platform | Value | Example |
45 /// | ------- | ----------------------------------------------- | ------------------------------------ |
46 /// | Linux | `$XDG_CACHE_HOME/zebra` or `$HOME/.cache/zebra` | `/home/alice/.cache/zebra` |
47 /// | macOS | `$HOME/Library/Caches/zebra` | `/Users/Alice/Library/Caches/zebra` |
48 /// | Windows | `{FOLDERID_LocalAppData}\zebra` | `C:\Users\Alice\AppData\Local\zebra` |
49 /// | Other | `std::env::current_dir()/cache/zebra` | `/cache/zebra` |
50 ///
51 /// # Security
52 ///
53 /// If you are running Zebra with elevated permissions ("root"), create the
54 /// directory for this file before running Zebra, and make sure the Zebra user
55 /// account has exclusive access to that directory, and other users can't modify
56 /// its parent directories.
57 ///
58 /// # Implementation Details
59 ///
60 /// Each state format version and network has a separate state.
61 /// These states are stored in `state/vN/mainnet` and `state/vN/testnet` subdirectories,
62 /// underneath the `cache_dir` path, where `N` is the state format version.
63 ///
64 /// When Zebra's state format changes, it creates a new state subdirectory for that version,
65 /// and re-syncs from genesis.
66 ///
67 /// Old state versions are automatically deleted at startup. You can also manually delete old
68 /// state versions.
69 pub cache_dir: PathBuf,
70
71 /// Whether to use an ephemeral database.
72 ///
73 /// Ephemeral databases are stored in a temporary directory created using [`tempfile::tempdir()`].
74 /// They are deleted when Zebra exits successfully.
75 /// (If Zebra panics or crashes, the ephemeral database won't be deleted.)
76 ///
77 /// Set to `false` by default. If this is set to `true`, [`cache_dir`] is ignored.
78 ///
79 /// Ephemeral directories are created in the [`std::env::temp_dir()`].
80 /// Zebra names each directory after the state version and network, for example: `zebra-state-v21-mainnet-XnyGnE`.
81 ///
82 /// [`cache_dir`]: struct.Config.html#structfield.cache_dir
83 pub ephemeral: bool,
84
85 /// Whether to cache non-finalized blocks on disk to be restored when Zebra restarts.
86 ///
87 /// Set to `true` by default. If this is set to `false`, Zebra will irrecoverably drop
88 /// non-finalized blocks when the process exits and will have to re-download them from
89 /// the network when it restarts, if those blocks are still available in the network.
90 ///
91 /// Note: The non-finalized state will be written to a backup cache once per 5 seconds at most.
92 /// If blocks are added to the non-finalized state more frequently, the backup may not reflect
93 /// Zebra's last non-finalized state before it shut down.
94 pub should_backup_non_finalized_state: bool,
95
96 /// Whether to delete the old database directories when present.
97 ///
98 /// Set to `true` by default. If this is set to `false`,
99 /// no check for old database versions will be made and nothing will be
100 /// deleted.
101 pub delete_old_database: bool,
102
103 // Debug configs
104 //
105 /// Commit blocks to the finalized state up to this height, then exit Zebra.
106 ///
107 /// Set to `None` by default: Zebra continues syncing indefinitely.
108 pub debug_stop_at_height: Option<u32>,
109
110 /// While Zebra is running, check state validity this often.
111 ///
112 /// Set to `None` by default: Zebra only checks state format validity on startup and shutdown.
113 #[serde(with = "humantime_serde")]
114 pub debug_validity_check_interval: Option<Duration>,
115
116 /// If true, skip spawning the non-finalized state backup task and instead write
117 /// the non-finalized state to the backup directory synchronously before each update
118 /// to the latest chain tip or non-finalized state channels.
119 ///
120 /// Set to `false` by default. When `true`, the non-finalized state is still restored
121 /// from the backup directory on startup, but updates are written synchronously on every
122 /// block commit rather than asynchronously every 5 seconds.
123 ///
124 /// This is intended for testing scenarios where blocks are committed rapidly and the
125 /// async backup task may not flush all blocks before shutdown.
126 pub debug_skip_non_finalized_state_backup_task: bool,
127}
128
129fn gen_temp_path(prefix: &str) -> PathBuf {
130 tempfile::Builder::new()
131 .prefix(prefix)
132 .tempdir()
133 .expect("temporary directory is created successfully")
134 .keep()
135}
136
137impl Config {
138 /// Returns the path for the database, based on the kind, major version and network.
139 /// Each incompatible database format or network gets its own unique path.
140 pub fn db_path(
141 &self,
142 db_kind: impl AsRef<str>,
143 major_version: u64,
144 network: &Network,
145 ) -> PathBuf {
146 let db_kind = db_kind.as_ref();
147 let major_version = format!("v{major_version}");
148 let net_dir = network.directory_name();
149
150 if self.ephemeral {
151 gen_temp_path(&format!("zebra-{db_kind}-{major_version}-{net_dir}-"))
152 } else {
153 self.cache_dir
154 .join(db_kind)
155 .join(major_version)
156 .join(net_dir)
157 }
158 }
159
160 /// Returns the path for the non-finalized state backup directory, based on the network.
161 /// Non-finalized state backup files are encoded in the network protocol format and remain
162 /// valid across db format upgrades.
163 pub fn non_finalized_state_backup_dir(&self, network: &Network) -> Option<PathBuf> {
164 if self.ephemeral || !self.should_backup_non_finalized_state {
165 // Ephemeral databases are intended to be irrecoverable across restarts and don't
166 // require a backup for the non-finalized state.
167 return None;
168 }
169
170 let net_dir = network.directory_name();
171 Some(self.cache_dir.join("non_finalized_state").join(net_dir))
172 }
173
174 /// Returns the path for the database format minor/patch version file,
175 /// based on the kind, major version and network.
176 pub fn version_file_path(
177 &self,
178 db_kind: impl AsRef<str>,
179 major_version: u64,
180 network: &Network,
181 ) -> PathBuf {
182 let mut version_path = self.db_path(db_kind, major_version, network);
183
184 version_path.push(DATABASE_FORMAT_VERSION_FILE_NAME);
185
186 version_path
187 }
188
189 /// Returns a config for a temporary database that is deleted when it is dropped.
190 pub fn ephemeral() -> Config {
191 Config {
192 ephemeral: true,
193 ..Config::default()
194 }
195 }
196}
197
198impl Default for Config {
199 fn default() -> Self {
200 Self {
201 cache_dir: default_cache_dir(),
202 ephemeral: false,
203 should_backup_non_finalized_state: true,
204 delete_old_database: true,
205 debug_stop_at_height: None,
206 debug_validity_check_interval: None,
207 debug_skip_non_finalized_state_backup_task: false,
208 }
209 }
210}
211
212// Cleaning up old database versions
213// TODO: put this in a different module?
214
215/// Spawns a task that checks if there are old state database folders,
216/// and deletes them from the filesystem.
217///
218/// See `check_and_delete_old_databases()` for details.
219pub fn check_and_delete_old_state_databases(config: &Config, network: &Network) -> JoinHandle<()> {
220 check_and_delete_old_databases(
221 config,
222 STATE_DATABASE_KIND,
223 state_database_format_version_in_code().major,
224 network,
225 )
226}
227
228/// Spawns a task that checks if there are old database folders,
229/// and deletes them from the filesystem.
230///
231/// Iterate over the files and directories in the databases folder and delete if:
232/// - The `db_kind` directory exists.
233/// - The entry in `db_kind` is a directory.
234/// - The directory name has a prefix `v`.
235/// - The directory name without the prefix can be parsed as an unsigned number.
236/// - The parsed number is lower than the `major_version`.
237///
238/// The network is used to generate the path, then ignored.
239/// If `config` is an ephemeral database, no databases are deleted.
240///
241/// # Panics
242///
243/// If the path doesn't match the expected `db_kind/major_version/network` format.
244pub fn check_and_delete_old_databases(
245 config: &Config,
246 db_kind: impl AsRef<str>,
247 major_version: u64,
248 network: &Network,
249) -> JoinHandle<()> {
250 let current_span = Span::current();
251 let config = config.clone();
252 let db_kind = db_kind.as_ref().to_string();
253 let network = network.clone();
254
255 spawn_blocking(move || {
256 current_span.in_scope(|| {
257 delete_old_databases(config, db_kind, major_version, &network);
258 info!("finished old database version cleanup task");
259 })
260 })
261}
262
263/// Check if there are old database folders and delete them from the filesystem.
264///
265/// See [`check_and_delete_old_databases`] for details.
266fn delete_old_databases(config: Config, db_kind: String, major_version: u64, network: &Network) {
267 if config.ephemeral || !config.delete_old_database {
268 return;
269 }
270
271 info!(db_kind, "checking for old database versions");
272
273 let restorable_db_versions = restorable_db_versions();
274
275 let mut db_path = config.db_path(&db_kind, major_version, network);
276 // Check and remove the network path.
277 assert_eq!(
278 db_path.file_name(),
279 Some(network.directory_name().as_ref()),
280 "unexpected database network path structure"
281 );
282 assert!(db_path.pop());
283
284 // Check and remove the major version path, we'll iterate over them all below.
285 assert_eq!(
286 db_path.file_name(),
287 Some(format!("v{major_version}").as_ref()),
288 "unexpected database version path structure"
289 );
290 assert!(db_path.pop());
291
292 // Check for the correct database kind to iterate within.
293 assert_eq!(
294 db_path.file_name(),
295 Some(db_kind.as_ref()),
296 "unexpected database kind path structure"
297 );
298
299 if let Some(db_kind_dir) = read_dir(&db_path) {
300 for entry in db_kind_dir.flatten() {
301 let deleted_db =
302 check_and_delete_database(&config, major_version, &restorable_db_versions, &entry);
303
304 if let Some(deleted_db) = deleted_db {
305 info!(?deleted_db, "deleted outdated {db_kind} database directory");
306 }
307 }
308 }
309}
310
311/// Return a `ReadDir` for `dir`, after checking that `dir` exists and can be read.
312///
313/// Returns `None` if any operation fails.
314fn read_dir(dir: &Path) -> Option<ReadDir> {
315 if dir.exists() {
316 if let Ok(read_dir) = dir.read_dir() {
317 return Some(read_dir);
318 }
319 }
320 None
321}
322
323/// Check if `entry` is an old database directory, and delete it from the filesystem.
324/// See [`check_and_delete_old_databases`] for details.
325///
326/// If the directory was deleted, returns its path.
327fn check_and_delete_database(
328 config: &Config,
329 major_version: u64,
330 restorable_db_versions: &[u64],
331 entry: &DirEntry,
332) -> Option<PathBuf> {
333 let dir_name = parse_dir_name(entry)?;
334 let dir_major_version = parse_major_version(&dir_name)?;
335
336 if dir_major_version >= major_version {
337 return None;
338 }
339
340 // Don't delete databases that can be reused.
341 if restorable_db_versions
342 .iter()
343 .map(|v| v - 1)
344 .any(|v| v == dir_major_version)
345 {
346 return None;
347 }
348
349 let outdated_path = entry.path();
350
351 // # Correctness
352 //
353 // Check that the path we're about to delete is inside the cache directory.
354 // If the user has symlinked the outdated state directory to a non-cache directory,
355 // we don't want to delete it, because it might contain other files.
356 //
357 // We don't attempt to guard against malicious symlinks created by attackers
358 // (TOCTOU attacks). Zebra should not be run with elevated privileges.
359 let cache_path = canonicalize(&config.cache_dir).ok()?;
360 let outdated_path = canonicalize(outdated_path).ok()?;
361
362 if !outdated_path.starts_with(&cache_path) {
363 info!(
364 skipped_path = ?outdated_path,
365 ?cache_path,
366 "skipped cleanup of outdated state directory: state is outside cache directory",
367 );
368
369 return None;
370 }
371
372 remove_dir_all(&outdated_path).ok().map(|()| outdated_path)
373}
374
375/// Check if `entry` is a directory with a valid UTF-8 name.
376/// (State directory names are guaranteed to be UTF-8.)
377///
378/// Returns `None` if any operation fails.
379fn parse_dir_name(entry: &DirEntry) -> Option<String> {
380 if let Ok(file_type) = entry.file_type() {
381 if file_type.is_dir() {
382 if let Ok(dir_name) = entry.file_name().into_string() {
383 return Some(dir_name);
384 }
385 }
386 }
387 None
388}
389
390/// Parse the database major version number from `dir_name`.
391///
392/// Returns `None` if parsing fails, or the directory name is not in the expected format.
393fn parse_major_version(dir_name: &str) -> Option<u64> {
394 dir_name
395 .strip_prefix('v')
396 .and_then(|version| version.parse().ok())
397}
398
399// TODO: move these to the format upgrade module
400
401/// Returns the full semantic version of the on-disk state database, based on its config and network.
402pub fn state_database_format_version_on_disk(
403 config: &Config,
404 network: &Network,
405) -> Result<Option<Version>, BoxError> {
406 database_format_version_on_disk(
407 config,
408 STATE_DATABASE_KIND,
409 state_database_format_version_in_code().major,
410 network,
411 )
412}
413
414/// Returns the full semantic version of the on-disk database, based on its config, kind, major version,
415/// and network.
416///
417/// Typically, the version is read from a version text file.
418///
419/// If there is an existing on-disk database, but no version file,
420/// returns `Ok(Some(major_version.0.0))`.
421/// (This happens even if the database directory was just newly created.)
422///
423/// If there is no existing on-disk database, or `config` is ephemeral, returns `Ok(None)`.
424///
425/// This is the format of the data on disk, the version
426/// implemented by the running Zebra code can be different.
427pub fn database_format_version_on_disk(
428 config: &Config,
429 db_kind: impl AsRef<str>,
430 major_version: u64,
431 network: &Network,
432) -> Result<Option<Version>, BoxError> {
433 // Each ephemeral database is created in a new temporary directory when it is opened.
434 if config.ephemeral {
435 return Ok(None);
436 }
437
438 let version_path = config.version_file_path(&db_kind, major_version, network);
439 let db_path = config.db_path(db_kind, major_version, network);
440
441 database_format_version_at_path(&version_path, &db_path, major_version)
442}
443
444/// Returns the full semantic version of the on-disk database at `version_path`.
445///
446/// See [`database_format_version_on_disk()`] for details.
447pub(crate) fn database_format_version_at_path(
448 version_path: &Path,
449 db_path: &Path,
450 major_version: u64,
451) -> Result<Option<Version>, BoxError> {
452 let disk_version_file = match fs::read_to_string(version_path) {
453 Ok(version) => Some(version),
454 Err(e) if e.kind() == ErrorKind::NotFound => {
455 // If the version file doesn't exist, don't guess the version yet.
456 None
457 }
458 Err(e) => Err(e)?,
459 };
460
461 // The database has a version file on disk
462 if let Some(version) = disk_version_file {
463 return Ok(Some(
464 version
465 .parse()
466 // Try to parse the previous format of the disk version file if it cannot be parsed as a `Version` directly.
467 .or_else(|err| {
468 format!("{major_version}.{version}")
469 .parse()
470 .map_err(|err2| format!("failed to parse format version: {err}, {err2}"))
471 })?,
472 ));
473 }
474
475 // There's no version file on disk, so we need to guess the version
476 // based on the database content
477 match fs::metadata(db_path) {
478 // But there is a database on disk, so it has the current major version with no upgrades.
479 // If the database directory was just newly created, we also return this version.
480 Ok(_metadata) => Ok(Some(Version::new(major_version, 0, 0))),
481
482 // There's no version file and no database on disk, so it's a new database.
483 // It will be created with the current version,
484 // but temporarily return the default version above until the version file is written.
485 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
486
487 Err(e) => Err(e)?,
488 }
489}
490
491// Hide this destructive method from the public API, except in tests.
492#[allow(unused_imports)]
493pub(crate) use hidden::{
494 write_database_format_version_at_path, write_database_format_version_to_disk,
495 write_state_database_format_version_to_disk,
496};
497
498pub(crate) mod hidden {
499 #![allow(dead_code)]
500
501 use zebra_chain::common::atomic_write;
502
503 use super::*;
504
505 /// Writes `changed_version` to the on-disk state database after the format is changed.
506 /// (Or a new database is created.)
507 ///
508 /// See `write_database_format_version_to_disk()` for details.
509 pub fn write_state_database_format_version_to_disk(
510 config: &Config,
511 changed_version: &Version,
512 network: &Network,
513 ) -> Result<(), BoxError> {
514 write_database_format_version_to_disk(
515 config,
516 STATE_DATABASE_KIND,
517 state_database_format_version_in_code().major,
518 changed_version,
519 network,
520 )
521 }
522
523 /// Writes `changed_version` to the on-disk database after the format is changed.
524 /// (Or a new database is created.)
525 ///
526 /// The database path is based on its kind, `major_version_in_code`, and network.
527 ///
528 /// # Correctness
529 ///
530 /// This should only be called:
531 /// - after each format upgrade is complete,
532 /// - when creating a new database, or
533 /// - when an older Zebra version opens a newer database.
534 ///
535 /// # Concurrency
536 ///
537 /// This must only be called while RocksDB has an open database for `config`.
538 /// Otherwise, multiple Zebra processes could write the version at the same time,
539 /// corrupting the file.
540 pub fn write_database_format_version_to_disk(
541 config: &Config,
542 db_kind: impl AsRef<str>,
543 major_version_in_code: u64,
544 changed_version: &Version,
545 network: &Network,
546 ) -> Result<(), BoxError> {
547 write_database_format_version_at_path(
548 config.version_file_path(db_kind, major_version_in_code, network),
549 changed_version,
550 )
551 }
552
553 /// Writes `changed_version` to the version file at `version_path`.
554 ///
555 /// See [`write_database_format_version_to_disk()`] for details.
556 pub(crate) fn write_database_format_version_at_path(
557 version_path: PathBuf,
558 changed_version: &Version,
559 ) -> Result<(), BoxError> {
560 // Write the version file atomically so the cache is not corrupted if Zebra shuts down or
561 // crashes.
562 atomic_write(version_path, changed_version.to_string().as_bytes())??;
563
564 Ok(())
565 }
566}