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 delete the old database directories when present.
86 ///
87 /// Set to `true` by default. If this is set to `false`,
88 /// no check for old database versions will be made and nothing will be
89 /// deleted.
90 pub delete_old_database: bool,
91
92 // Debug configs
93 //
94 /// Commit blocks to the finalized state up to this height, then exit Zebra.
95 ///
96 /// Set to `None` by default: Zebra continues syncing indefinitely.
97 pub debug_stop_at_height: Option<u32>,
98
99 /// While Zebra is running, check state validity this often.
100 ///
101 /// Set to `None` by default: Zebra only checks state format validity on startup and shutdown.
102 #[serde(with = "humantime_serde")]
103 pub debug_validity_check_interval: Option<Duration>,
104
105 // Elasticsearch configs
106 //
107 #[cfg(feature = "elasticsearch")]
108 /// The elasticsearch database url.
109 pub elasticsearch_url: String,
110
111 #[cfg(feature = "elasticsearch")]
112 /// The elasticsearch database username.
113 pub elasticsearch_username: String,
114
115 #[cfg(feature = "elasticsearch")]
116 /// The elasticsearch database password.
117 pub elasticsearch_password: String,
118}
119
120fn gen_temp_path(prefix: &str) -> PathBuf {
121 tempfile::Builder::new()
122 .prefix(prefix)
123 .tempdir()
124 .expect("temporary directory is created successfully")
125 .into_path()
126}
127
128impl Config {
129 /// Returns the path for the database, based on the kind, major version and network.
130 /// Each incompatible database format or network gets its own unique path.
131 pub fn db_path(
132 &self,
133 db_kind: impl AsRef<str>,
134 major_version: u64,
135 network: &Network,
136 ) -> PathBuf {
137 let db_kind = db_kind.as_ref();
138 let major_version = format!("v{}", major_version);
139 let net_dir = network.lowercase_name();
140
141 if self.ephemeral {
142 gen_temp_path(&format!("zebra-{db_kind}-{major_version}-{net_dir}-"))
143 } else {
144 self.cache_dir
145 .join(db_kind)
146 .join(major_version)
147 .join(net_dir)
148 }
149 }
150
151 /// Returns the path for the database format minor/patch version file,
152 /// based on the kind, major version and network.
153 pub fn version_file_path(
154 &self,
155 db_kind: impl AsRef<str>,
156 major_version: u64,
157 network: &Network,
158 ) -> PathBuf {
159 let mut version_path = self.db_path(db_kind, major_version, network);
160
161 version_path.push(DATABASE_FORMAT_VERSION_FILE_NAME);
162
163 version_path
164 }
165
166 /// Returns a config for a temporary database that is deleted when it is dropped.
167 pub fn ephemeral() -> Config {
168 Config {
169 ephemeral: true,
170 ..Config::default()
171 }
172 }
173}
174
175impl Default for Config {
176 fn default() -> Self {
177 Self {
178 cache_dir: default_cache_dir(),
179 ephemeral: false,
180 delete_old_database: true,
181 debug_stop_at_height: None,
182 debug_validity_check_interval: None,
183 #[cfg(feature = "elasticsearch")]
184 elasticsearch_url: "https://localhost:9200".to_string(),
185 #[cfg(feature = "elasticsearch")]
186 elasticsearch_username: "elastic".to_string(),
187 #[cfg(feature = "elasticsearch")]
188 elasticsearch_password: "".to_string(),
189 }
190 }
191}
192
193// Cleaning up old database versions
194// TODO: put this in a different module?
195
196/// Spawns a task that checks if there are old state database folders,
197/// and deletes them from the filesystem.
198///
199/// See `check_and_delete_old_databases()` for details.
200pub fn check_and_delete_old_state_databases(config: &Config, network: &Network) -> JoinHandle<()> {
201 check_and_delete_old_databases(
202 config,
203 STATE_DATABASE_KIND,
204 state_database_format_version_in_code().major,
205 network,
206 )
207}
208
209/// Spawns a task that checks if there are old database folders,
210/// and deletes them from the filesystem.
211///
212/// Iterate over the files and directories in the databases folder and delete if:
213/// - The `db_kind` directory exists.
214/// - The entry in `db_kind` is a directory.
215/// - The directory name has a prefix `v`.
216/// - The directory name without the prefix can be parsed as an unsigned number.
217/// - The parsed number is lower than the `major_version`.
218///
219/// The network is used to generate the path, then ignored.
220/// If `config` is an ephemeral database, no databases are deleted.
221///
222/// # Panics
223///
224/// If the path doesn't match the expected `db_kind/major_version/network` format.
225pub fn check_and_delete_old_databases(
226 config: &Config,
227 db_kind: impl AsRef<str>,
228 major_version: u64,
229 network: &Network,
230) -> JoinHandle<()> {
231 let current_span = Span::current();
232 let config = config.clone();
233 let db_kind = db_kind.as_ref().to_string();
234 let network = network.clone();
235
236 spawn_blocking(move || {
237 current_span.in_scope(|| {
238 delete_old_databases(config, db_kind, major_version, &network);
239 info!("finished old database version cleanup task");
240 })
241 })
242}
243
244/// Check if there are old database folders and delete them from the filesystem.
245///
246/// See [`check_and_delete_old_databases`] for details.
247fn delete_old_databases(config: Config, db_kind: String, major_version: u64, network: &Network) {
248 if config.ephemeral || !config.delete_old_database {
249 return;
250 }
251
252 info!(db_kind, "checking for old database versions");
253
254 let mut db_path = config.db_path(&db_kind, major_version, network);
255 // Check and remove the network path.
256 assert_eq!(
257 db_path.file_name(),
258 Some(network.lowercase_name().as_ref()),
259 "unexpected database network path structure"
260 );
261 assert!(db_path.pop());
262
263 // Check and remove the major version path, we'll iterate over them all below.
264 assert_eq!(
265 db_path.file_name(),
266 Some(format!("v{major_version}").as_ref()),
267 "unexpected database version path structure"
268 );
269 assert!(db_path.pop());
270
271 // Check for the correct database kind to iterate within.
272 assert_eq!(
273 db_path.file_name(),
274 Some(db_kind.as_ref()),
275 "unexpected database kind path structure"
276 );
277
278 if let Some(db_kind_dir) = read_dir(&db_path) {
279 for entry in db_kind_dir.flatten() {
280 let deleted_db = check_and_delete_database(&config, major_version, &entry);
281
282 if let Some(deleted_db) = deleted_db {
283 info!(?deleted_db, "deleted outdated {db_kind} database directory");
284 }
285 }
286 }
287}
288
289/// Return a `ReadDir` for `dir`, after checking that `dir` exists and can be read.
290///
291/// Returns `None` if any operation fails.
292fn read_dir(dir: &Path) -> Option<ReadDir> {
293 if dir.exists() {
294 if let Ok(read_dir) = dir.read_dir() {
295 return Some(read_dir);
296 }
297 }
298 None
299}
300
301/// Check if `entry` is an old database directory, and delete it from the filesystem.
302/// See [`check_and_delete_old_databases`] for details.
303///
304/// If the directory was deleted, returns its path.
305fn check_and_delete_database(
306 config: &Config,
307 major_version: u64,
308 entry: &DirEntry,
309) -> Option<PathBuf> {
310 let dir_name = parse_dir_name(entry)?;
311 let dir_major_version = parse_major_version(&dir_name)?;
312
313 if dir_major_version >= major_version {
314 return None;
315 }
316
317 // Don't delete databases that can be reused.
318 if restorable_db_versions()
319 .iter()
320 .map(|v| v - 1)
321 .any(|v| v == dir_major_version)
322 {
323 return None;
324 }
325
326 let outdated_path = entry.path();
327
328 // # Correctness
329 //
330 // Check that the path we're about to delete is inside the cache directory.
331 // If the user has symlinked the outdated state directory to a non-cache directory,
332 // we don't want to delete it, because it might contain other files.
333 //
334 // We don't attempt to guard against malicious symlinks created by attackers
335 // (TOCTOU attacks). Zebra should not be run with elevated privileges.
336 let cache_path = canonicalize(&config.cache_dir).ok()?;
337 let outdated_path = canonicalize(outdated_path).ok()?;
338
339 if !outdated_path.starts_with(&cache_path) {
340 info!(
341 skipped_path = ?outdated_path,
342 ?cache_path,
343 "skipped cleanup of outdated state directory: state is outside cache directory",
344 );
345
346 return None;
347 }
348
349 remove_dir_all(&outdated_path).ok().map(|()| outdated_path)
350}
351
352/// Check if `entry` is a directory with a valid UTF-8 name.
353/// (State directory names are guaranteed to be UTF-8.)
354///
355/// Returns `None` if any operation fails.
356fn parse_dir_name(entry: &DirEntry) -> Option<String> {
357 if let Ok(file_type) = entry.file_type() {
358 if file_type.is_dir() {
359 if let Ok(dir_name) = entry.file_name().into_string() {
360 return Some(dir_name);
361 }
362 }
363 }
364 None
365}
366
367/// Parse the database major version number from `dir_name`.
368///
369/// Returns `None` if parsing fails, or the directory name is not in the expected format.
370fn parse_major_version(dir_name: &str) -> Option<u64> {
371 dir_name
372 .strip_prefix('v')
373 .and_then(|version| version.parse().ok())
374}
375
376// TODO: move these to the format upgrade module
377
378/// Returns the full semantic version of the on-disk state database, based on its config and network.
379pub fn state_database_format_version_on_disk(
380 config: &Config,
381 network: &Network,
382) -> Result<Option<Version>, BoxError> {
383 database_format_version_on_disk(
384 config,
385 STATE_DATABASE_KIND,
386 state_database_format_version_in_code().major,
387 network,
388 )
389}
390
391/// Returns the full semantic version of the on-disk database, based on its config, kind, major version,
392/// and network.
393///
394/// Typically, the version is read from a version text file.
395///
396/// If there is an existing on-disk database, but no version file,
397/// returns `Ok(Some(major_version.0.0))`.
398/// (This happens even if the database directory was just newly created.)
399///
400/// If there is no existing on-disk database, returns `Ok(None)`.
401///
402/// This is the format of the data on disk, the version
403/// implemented by the running Zebra code can be different.
404pub fn database_format_version_on_disk(
405 config: &Config,
406 db_kind: impl AsRef<str>,
407 major_version: u64,
408 network: &Network,
409) -> Result<Option<Version>, BoxError> {
410 let version_path = config.version_file_path(&db_kind, major_version, network);
411 let db_path = config.db_path(db_kind, major_version, network);
412
413 database_format_version_at_path(&version_path, &db_path, major_version)
414}
415
416/// Returns the full semantic version of the on-disk database at `version_path`.
417///
418/// See [`database_format_version_on_disk()`] for details.
419pub(crate) fn database_format_version_at_path(
420 version_path: &Path,
421 db_path: &Path,
422 major_version: u64,
423) -> Result<Option<Version>, BoxError> {
424 let disk_version_file = match fs::read_to_string(version_path) {
425 Ok(version) => Some(version),
426 Err(e) if e.kind() == ErrorKind::NotFound => {
427 // If the version file doesn't exist, don't guess the version yet.
428 None
429 }
430 Err(e) => Err(e)?,
431 };
432
433 // The database has a version file on disk
434 if let Some(version) = disk_version_file {
435 return Ok(Some(
436 version
437 .parse()
438 // Try to parse the previous format of the disk version file if it cannot be parsed as a `Version` directly.
439 .or_else(|err| {
440 format!("{major_version}.{version}")
441 .parse()
442 .map_err(|err2| format!("failed to parse format version: {err}, {err2}"))
443 })?,
444 ));
445 }
446
447 // There's no version file on disk, so we need to guess the version
448 // based on the database content
449 match fs::metadata(db_path) {
450 // But there is a database on disk, so it has the current major version with no upgrades.
451 // If the database directory was just newly created, we also return this version.
452 Ok(_metadata) => Ok(Some(Version::new(major_version, 0, 0))),
453
454 // There's no version file and no database on disk, so it's a new database.
455 // It will be created with the current version,
456 // but temporarily return the default version above until the version file is written.
457 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
458
459 Err(e) => Err(e)?,
460 }
461}
462
463// Hide this destructive method from the public API, except in tests.
464#[allow(unused_imports)]
465pub(crate) use hidden::{
466 write_database_format_version_to_disk, write_state_database_format_version_to_disk,
467};
468
469pub(crate) mod hidden {
470 #![allow(dead_code)]
471
472 use zebra_chain::common::atomic_write;
473
474 use super::*;
475
476 /// Writes `changed_version` to the on-disk state database after the format is changed.
477 /// (Or a new database is created.)
478 ///
479 /// See `write_database_format_version_to_disk()` for details.
480 pub fn write_state_database_format_version_to_disk(
481 config: &Config,
482 changed_version: &Version,
483 network: &Network,
484 ) -> Result<(), BoxError> {
485 write_database_format_version_to_disk(
486 config,
487 STATE_DATABASE_KIND,
488 state_database_format_version_in_code().major,
489 changed_version,
490 network,
491 )
492 }
493
494 /// Writes `changed_version` to the on-disk database after the format is changed.
495 /// (Or a new database is created.)
496 ///
497 /// The database path is based on its kind, `major_version_in_code`, and network.
498 ///
499 /// # Correctness
500 ///
501 /// This should only be called:
502 /// - after each format upgrade is complete,
503 /// - when creating a new database, or
504 /// - when an older Zebra version opens a newer database.
505 ///
506 /// # Concurrency
507 ///
508 /// This must only be called while RocksDB has an open database for `config`.
509 /// Otherwise, multiple Zebra processes could write the version at the same time,
510 /// corrupting the file.
511 pub fn write_database_format_version_to_disk(
512 config: &Config,
513 db_kind: impl AsRef<str>,
514 major_version_in_code: u64,
515 changed_version: &Version,
516 network: &Network,
517 ) -> Result<(), BoxError> {
518 // Write the version file atomically so the cache is not corrupted if Zebra shuts down or
519 // crashes.
520 atomic_write(
521 config.version_file_path(db_kind, major_version_in_code, network),
522 changed_version.to_string().as_bytes(),
523 )??;
524
525 Ok(())
526 }
527}