zebra_state/service/finalized_state/zebra_db.rs
1//! Provides high-level access to the database using [`zebra_chain`] types.
2//!
3//! This module makes sure that:
4//! - all disk writes happen inside a RocksDB transaction, and
5//! - format-specific invariants are maintained.
6//!
7//! # Correctness
8//!
9//! [`crate::constants::state_database_format_version_in_code()`] must be incremented
10//! each time the database format (column, serialization, etc) changes.
11
12use std::{
13 path::{Path, PathBuf},
14 sync::Arc,
15};
16
17use crossbeam_channel::bounded;
18use semver::Version;
19
20use zebra_chain::{block::Height, diagnostic::task::WaitForPanics, parameters::Network};
21
22use crate::{
23 config::{
24 database_format_version_at_path, database_format_version_on_disk,
25 write_database_format_version_at_path,
26 },
27 constants::DATABASE_FORMAT_VERSION_FILE_NAME,
28 service::finalized_state::{
29 disk_db::DiskDb,
30 disk_format::{
31 block::MAX_ON_DISK_HEIGHT,
32 transparent::AddressLocation,
33 upgrade::{DbFormatChange, DbFormatChangeThreadHandle},
34 },
35 },
36 BoxError, Config, StateInitError,
37};
38
39use super::disk_format::upgrade::restorable_db_versions;
40
41pub mod block;
42pub mod chain;
43pub mod metrics;
44pub mod shielded;
45pub mod transparent;
46
47#[cfg(any(test, feature = "proptest-impl"))]
48// TODO: when the database is split out of zebra-state, always expose these methods.
49pub mod arbitrary;
50
51/// Wrapper struct to ensure high-level `zebra-state` database access goes through the correct API.
52///
53/// `rocksdb` allows concurrent writes through a shared reference,
54/// so database instances are cloneable. When the final clone is dropped,
55/// the database is closed.
56#[derive(Clone, Debug)]
57pub struct ZebraDb {
58 // Configuration
59 //
60 // This configuration cannot be modified after the database is initialized,
61 // because some clones would have different values.
62 //
63 /// The configuration for the database.
64 //
65 // TODO: move the config to DiskDb
66 config: Arc<Config>,
67
68 /// Should format upgrades and format checks be skipped for this instance?
69 /// Only used in test code.
70 //
71 // TODO: move this to DiskDb
72 debug_skip_format_upgrades: bool,
73
74 // Owned State
75 //
76 // Everything contained in this state must be shared by all clones, or read-only.
77 //
78 /// A handle to a running format change task, which cancels the task when dropped.
79 ///
80 /// # Concurrency
81 ///
82 /// This field should be dropped before the database field, so the format upgrade task is
83 /// cancelled before the database is dropped. This helps avoid some kinds of deadlocks.
84 //
85 // TODO: move the generic upgrade code and fields to DiskDb
86 format_change_handle: Option<DbFormatChangeThreadHandle>,
87
88 /// The inner low-level database wrapper for the RocksDB database.
89 db: DiskDb,
90}
91
92impl ZebraDb {
93 /// Opens or creates the database at a path based on the kind, major version and network,
94 /// with the supplied column families, preserving any existing column families,
95 /// and returns a shared high-level typed database wrapper.
96 ///
97 /// If `debug_skip_format_upgrades` is true, don't do any format upgrades or format checks.
98 /// This argument is only used in tests or with `proptest-impl`, and is ignored otherwise.
99 //
100 // TODO: rename to StateDb and remove the db_kind and column_families_in_code arguments
101 #[allow(clippy::unwrap_in_result)]
102 pub fn new(
103 config: &Config,
104 db_kind: impl AsRef<str>,
105 format_version_in_code: &Version,
106 network: &Network,
107 debug_skip_format_upgrades: bool,
108 column_families_in_code: impl IntoIterator<Item = String>,
109 read_only: bool,
110 ) -> Result<ZebraDb, StateInitError> {
111 // A read-only secondary instance must never modify the primary's cache directory, so it
112 // skips the post-major-upgrade DB reuse (which can create directories and rename the
113 // on-disk database) and reads the on-disk format version directly. The cache directory is
114 // checked for readability first, so a missing or unreadable directory returns a typed
115 // `ReadOnlyCacheDirUnreadable` error here instead of panicking on the version-file read.
116 let disk_version = if read_only {
117 // While this check is also done in `DiskDB::new()` below, we must
118 // repeat it here because the `check_cache_dir_readable()` call just
119 // after this will look into `cache_dir` but that should be ignored
120 // when `ephemeral` is true.
121 if config.ephemeral {
122 return Err(StateInitError::ReadOnlyEphemeralConflict);
123 }
124
125 DiskDb::check_cache_dir_readable(&config.cache_dir)?;
126
127 database_format_version_on_disk(config, &db_kind, format_version_in_code.major, network)
128 .expect("unable to read database format version file")
129 } else if config.ephemeral {
130 // An ephemeral database lives in a new temporary directory, so it is always new.
131 None
132 } else {
133 DiskDb::try_reusing_previous_db_after_major_upgrade(
134 &restorable_db_versions(),
135 format_version_in_code,
136 config,
137 &db_kind,
138 network,
139 )
140 .or_else(|| {
141 database_format_version_on_disk(
142 config,
143 &db_kind,
144 format_version_in_code.major,
145 network,
146 )
147 .expect("unable to read database format version file")
148 })
149 };
150
151 // Log any format changes before opening the database, in case opening fails.
152 let format_change = DbFormatChange::open_database(format_version_in_code, disk_version);
153
154 // A read-only secondary instance cannot create a database. If there's no database on
155 // disk, fail with a clear, actionable error instead of silently "creating" one.
156 //
157 // The read-write path is unaffected: creating a new database is the correct behavior there.
158 if read_only && format_change.is_newly_created() {
159 let db_path = config.db_path(&db_kind, format_version_in_code.major, network);
160 return Err(StateInitError::ReadOnlyDatabaseNotFound { path: db_path });
161 }
162
163 // Format upgrades try to write to the database, so we always skip them
164 // if `read_only` is `true`.
165 //
166 // We also allow skipping them in unit tests and dependent crates' test fixtures.
167 let debug_skip_format_upgrades =
168 read_only || (cfg!(any(test, feature = "proptest-impl")) && debug_skip_format_upgrades);
169
170 // Open the low-level database and do initial checks.
171 //
172 // After the database directory is created, a newly created database temporarily
173 // changes to the default database version. Then we set the correct version in the
174 // upgrade thread. We need to do the version change in this order, because the version
175 // file can only be changed while we hold the RocksDB database lock.
176 let disk_db = DiskDb::new(
177 config,
178 db_kind,
179 format_version_in_code,
180 network,
181 column_families_in_code,
182 read_only,
183 )?;
184
185 let mut db = ZebraDb {
186 config: Arc::new(config.clone()),
187 debug_skip_format_upgrades,
188 format_change_handle: None,
189 db: disk_db,
190 };
191
192 // One entry is enough to detect the corruption, and the height range has to start at
193 // zero, because the corrupt entries are exactly the ones at the zero address location.
194 let zero_location_utxos = db.address_utxo_locations(
195 AddressLocation::from_usize(Height(0), 0, 0),
196 Height(0)..=Height::MAX,
197 Some(1),
198 );
199 if !zero_location_utxos.is_empty() {
200 warn!(
201 "You have been impacted by the Zebra 2.4.0 address indexer corruption bug. \
202 If you rely on the data from the RPC interface, you will need to recover your database. \
203 Follow the instructions in the 2.4.1 release notes: https://github.com/ZcashFoundation/zebra/releases/tag/v2.4.1 \
204 If you just run the node for consensus and don't use data from the RPC interface, you can ignore this warning."
205 )
206 }
207
208 db.spawn_format_change(format_change);
209
210 Ok(db)
211 }
212
213 /// Launch any required format changes or format checks, and store their thread handle.
214 pub fn spawn_format_change(&mut self, format_change: DbFormatChange) {
215 if self.debug_skip_format_upgrades {
216 return;
217 }
218
219 // We have to get this height before we spawn the upgrade task, because threads can take
220 // a while to start, and new blocks can be committed as soon as we return from this method.
221 let initial_tip_height = self.finalized_tip_height();
222
223 // `upgrade_db` is a special clone of this database, which can't be used to shut down
224 // the upgrade task. (Because the task hasn't been launched yet,
225 // its `db.format_change_handle` is always None.)
226 let upgrade_db = self.clone();
227
228 // TODO:
229 // - should debug_stop_at_height wait for the upgrade task to finish?
230 let format_change_handle =
231 format_change.spawn_format_change(upgrade_db, initial_tip_height);
232
233 self.format_change_handle = Some(format_change_handle);
234 }
235
236 /// Sets `finished_format_upgrades` to true on the inner [`DiskDb`] to indicate that Zebra has
237 /// finished applying any required db format upgrades.
238 pub fn mark_finished_format_upgrades(&self) {
239 self.db.mark_finished_format_upgrades();
240 }
241
242 /// Returns true if the `finished_format_upgrades` flag has been set to true on the inner [`DiskDb`] to
243 /// indicate that Zebra has finished applying any required db format upgrades.
244 pub fn finished_format_upgrades(&self) -> bool {
245 self.db.finished_format_upgrades()
246 }
247
248 /// Returns config for this database.
249 pub fn config(&self) -> &Config {
250 &self.config
251 }
252
253 /// Returns the configured database kind for this database.
254 pub fn db_kind(&self) -> String {
255 self.db.db_kind()
256 }
257
258 /// Returns the format version of the running code that created this `ZebraDb` instance in memory.
259 pub fn format_version_in_code(&self) -> Version {
260 self.db.format_version_in_code()
261 }
262
263 /// Returns the fixed major version for this database.
264 pub fn major_version(&self) -> u64 {
265 self.db.major_version()
266 }
267
268 /// Returns the format version of this database on disk.
269 ///
270 /// See `database_format_version_on_disk()` for details.
271 pub fn format_version_on_disk(&self) -> Result<Option<Version>, BoxError> {
272 database_format_version_at_path(
273 &self.version_file_path(),
274 self.path(),
275 self.major_version(),
276 )
277 }
278
279 /// Updates the format of this database on disk to the suppled version.
280 ///
281 /// See `write_database_format_version_to_disk()` for details.
282 pub(crate) fn update_format_version_on_disk(
283 &self,
284 new_version: &Version,
285 ) -> Result<(), BoxError> {
286 write_database_format_version_at_path(self.version_file_path(), new_version)
287 }
288
289 /// Returns the path of this database's format version file.
290 ///
291 /// An ephemeral config gives every [`Config::db_path`] call a new temporary directory, so the
292 /// version file path comes from the path of the open database instead.
293 fn version_file_path(&self) -> PathBuf {
294 self.path().join(DATABASE_FORMAT_VERSION_FILE_NAME)
295 }
296
297 /// Returns the configured network for this database.
298 pub fn network(&self) -> Network {
299 self.db.network()
300 }
301
302 /// Returns the `Path` where the files used by this database are located.
303 pub fn path(&self) -> &Path {
304 self.db.path()
305 }
306
307 /// Check for panics in code running in spawned threads.
308 /// If a thread exited with a panic, resume that panic.
309 ///
310 /// This method should be called regularly, so that panics are detected as soon as possible.
311 pub fn check_for_panics(&mut self) {
312 if let Some(format_change_handle) = self.format_change_handle.as_mut() {
313 format_change_handle.check_for_panics();
314 }
315 }
316
317 /// When called with a secondary DB instance, tries to catch up with the primary DB instance
318 pub fn try_catch_up_with_primary(&self) -> Result<(), rocksdb::Error> {
319 self.db.try_catch_up_with_primary()
320 }
321
322 /// Spawns a blocking task to try catching up with the primary DB instance.
323 pub async fn spawn_try_catch_up_with_primary(&self) -> Result<(), rocksdb::Error> {
324 let db = self.clone();
325 tokio::task::spawn_blocking(move || {
326 let result = db.try_catch_up_with_primary();
327 if let Err(catch_up_error) = &result {
328 tracing::warn!(?catch_up_error, "failed to catch up to primary");
329 }
330 result
331 })
332 .wait_for_panics()
333 .await
334 }
335
336 /// Shut down the database, cleaning up background tasks and ephemeral data.
337 ///
338 /// If `force` is true, clean up regardless of any shared references.
339 /// `force` can cause errors accessing the database from other shared references.
340 /// It should only be used in debugging or test code, immediately before a manual shutdown.
341 ///
342 /// See [`DiskDb::shutdown`] for details.
343 pub fn shutdown(&mut self, force: bool) {
344 // Are we shutting down the underlying database instance?
345 let is_shutdown = force || self.db.shared_database_owners() <= 1;
346
347 // # Concurrency
348 //
349 // The format upgrade task should be cancelled before the database is flushed or shut down.
350 // This helps avoid some kinds of deadlocks.
351 //
352 // See also the correctness note in `DiskDb::shutdown()`.
353 if !self.debug_skip_format_upgrades && is_shutdown {
354 if let Some(format_change_handle) = self.format_change_handle.as_mut() {
355 format_change_handle.force_cancel();
356
357 // An ephemeral database's files are deleted below, and the format change thread
358 // reads and writes its version file, so the thread has to stop first.
359 if self.config.ephemeral {
360 format_change_handle.wait_for_exit();
361 }
362 }
363
364 // # Correctness
365 //
366 // Check that the database format is correct before shutting down.
367 // This lets users know to delete and re-sync their database immediately,
368 // rather than surprising them next time Zebra starts up.
369 //
370 // # Testinng
371 //
372 // In Zebra's CI, panicking here stops us writing invalid cached states,
373 // which would then make unrelated PRs fail when Zebra starts up.
374
375 // If the upgrade has completed, or we've done a downgrade, check the state is valid.
376 let disk_version = self
377 .format_version_on_disk()
378 .expect("unexpected invalid or unreadable database version file");
379
380 if let Some(disk_version) = disk_version {
381 // We need to keep the cancel handle until the format check has finished,
382 // because dropping it cancels the format check.
383 let (_never_cancel_handle, never_cancel_receiver) = bounded(1);
384
385 // We block here because the checks are quick and database validity is
386 // consensus-critical.
387 if disk_version >= self.db.format_version_in_code() {
388 DbFormatChange::check_new_blocks(self)
389 .run_format_change_or_check(
390 self,
391 // The initial tip height is not used by the new blocks format check.
392 None,
393 &never_cancel_receiver,
394 )
395 .expect("cancel handle is never used");
396 }
397 }
398 }
399
400 self.check_for_panics();
401
402 self.db.shutdown(force);
403 }
404
405 /// Check that the on-disk height is well below the maximum supported database height.
406 ///
407 /// Zebra only supports on-disk heights up to 3 bytes.
408 ///
409 /// # Logs an Error
410 ///
411 /// If Zebra is storing block heights that are close to [`MAX_ON_DISK_HEIGHT`].
412 pub(crate) fn check_max_on_disk_tip_height(&self) -> Result<(), String> {
413 if let Some((tip_height, tip_hash)) = self.tip() {
414 if tip_height.0 > MAX_ON_DISK_HEIGHT.0 / 2 {
415 let err = Err(format!(
416 "unexpectedly large tip height, database format upgrade required: \
417 tip height: {tip_height:?}, tip hash: {tip_hash:?}, \
418 max height: {MAX_ON_DISK_HEIGHT:?}"
419 ));
420 error!(?err);
421 return err;
422 }
423 }
424
425 Ok(())
426 }
427
428 /// Logs metrics related to the underlying RocksDB instance.
429 ///
430 /// This function prints various metrics and statistics about the RocksDB database,
431 /// such as disk usage, memory usage, and other performance-related metrics.
432 pub fn print_db_metrics(&self) {
433 self.db.print_db_metrics();
434 }
435
436 /// Exports RocksDB metrics to Prometheus.
437 ///
438 /// This function collects database statistics and exposes them as Prometheus metrics.
439 /// Call this periodically (e.g., every 30 seconds) from a background task.
440 pub(crate) fn export_metrics(&self) {
441 self.db.export_metrics();
442 }
443
444 /// Returns the estimated total disk space usage of the database.
445 pub fn size(&self) -> u64 {
446 self.db.size()
447 }
448}
449
450impl Drop for ZebraDb {
451 fn drop(&mut self) {
452 self.shutdown(false);
453 }
454}